Match regex and assign results in single line of code

Viewed 74833

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?

9 Answers

From Perl Cookbook 2nd ed 6.1 Copying and Substituting Simultaneously

$dst = $src;
$dst =~ s/this/that/;

becomes

($dst = $src) =~ s/this/that/;

I just assumed everyone did it this way, amazed that no one gave this answer.

Also, to amplify the accepted answer using the ternary operator to allow you to specify a default if there is no match:

my $match = $variable =~ /(*pattern*).*/ ? $1 : *defaultValue*;
Related