Keep the first 2 parts of the string having a separator

  • A+
Category:Languages

Is there a more succinct/perlish way for the following:

my @components = split /-/, $original; my $final_string = $components[0]."-".$components[1];   

Input is a string with at most 2 - and the last is optional. I always want to keep the first part. I.e. 10-9-1 should become 10-9 and 10-9 as input should remain 10-9

 


use Modern::Perl;  my $re = qr/-/d+/K.*$/; while(<DATA>) {     chomp;     s/$re//;     say; } __DATA__ 10-9-1 10-9 

For just a string:

my $original = '10-9-1'; (my $final = $original) =~ s/-/d+/K.*$//; say $final; 

Explantion:

s/     -       # find the first dash in the string     /d+     # 1 or more digits     /K      # forget all we have seen until this posiiton     .*      # rest of the line     $       # end of line // 

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: