Re: perl extracting substrings from string



Dean G. wrote:
archilleswaterland@xxxxxxxxxxx wrote:
$tina = abc_mn123_ln1xy8_dkxhs

I want to get

$mnval = 123;
$lnval = 1;
$xyval = 8;

Try this :

($trash,$mnval,$lnval,$xyval) = split /\D+/ $tina;

This splits on any set of non-digit characters, and unless it starts
with a digit, the first value will always be empty and thus "trash".

Right off the top, in Perl there's no need to set something you don't
want to a $trash variable you never use. just assign to undef, as in:

(undef,$mnval,$lnval,$xyval) = split /\D+/ $tina;

Second, I think that in this case it's a better approach to capture
what you want, rather than split on what you don't. Given only this
one example string, this is what I'd do:

my %values;
@values{ qw[mn ln xy] } = $tina =~ m{ \d+ }xg;

-jp

PS: who's Tina?

.