Question

Match regex and assign results in single line of code

I want to be able to do a regex match on a variable and assign the results to the variable itself. What is the best way to do it?

I want to essentially combine lines 2 and 3 in a single line of code:

$variable = "some string";
$variable =~ /(find something).*/;
$variable = $1;

Is there a shorter/simpler way to do this? Am I missing something?

 45  79088  45
1 Jan 1970

Solution

 63
my($variable) = "some string" =~ /(e\s*str)/;

This works because

If the /g option is not used, m// in list context returns a list consisting of the subexpressions matched by the parentheses in the pattern, i.e., ($1, $2, $3 …).

and because my($variable) = ... (note the parentheses around the scalar) supplies list context to the match.

If the pattern fails to match, $variable gets the undefined value.

2010-09-06

Solution

 32

Why do you want it to be shorter? Does is really matter?

$variable = $1 if $variable =~ /(find something).*/;

If you are worried about the variable name or doing this repeatedly, wrap the thing in a subroutine and forget about it:

 some_sub( $variable, qr/pattern/ );
 sub some_sub { $_[0] = $1 if eval { $_[0] =~ m/$_[1]/ }; $1 };

However you implement it, the point of the subroutine is to make it reuseable so you give a particular set of lines a short name that stands in their place.


Several other answers mention a destructive substitution:

( my $new = $variable ) =~ s/pattern/replacement/;

I tend to keep the original data around, and Perl v5.14 has an /r flag that leaves the original alone and returns a new string with the replacement (instead of the count of replacements):

my $match = $variable =~ s/pattern/replacement/r;
2010-09-06