[tpm] Regex question
arocker at vex.net
arocker at vex.net
Wed Jul 9 08:51:32 PDT 2008
Madi's original question, and one typical response:
>> my $foo="ABC-987-01";
>> my $bar=$foo;
>> $bar=~s/(\w+-\d+)-\d+/$1/;
>> # $bar now 'ABC-987'.
>>
>> That's three lines. Is there a way to do this in one line?
>
> Maybe I misunderstood the question... You can say
>
> my ($bar) = $foo =~ /(\w+-\d+)-\d+/;
>
> which will assing $1 to $bar if the match succeeds.
>
Compressing the assignment (which really doesn't include the original
setting of $foo) saves one line ad one naming of $bar at the expense of
complexity and inflexibility.
To comprehend the expression, you have to keep an extra level on the
mental stack, and if you want to change the destination you risk changing
the regex. (The two expressions aren't completely equivalent; the original
doesn't change $foo, the other, like most of the suggestions, does.)
Sometimes, it pays to remember the KISS principle, and the joke (?) about
a gentleman being a man who knows how to play the accordion, but doesn't.
More information about the toronto-pm
mailing list