Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I extract the matches from the Perl match operator into variables?

Tags:

perl

If I have a match operator, how do I save the parts of the strings captured in the parentheses in variables instead of using $1, $2, and so on?

... = m/stuff (.*) stuff/;

What goes on the left?

like image 627
joachim Avatar asked Nov 02 '09 13:11

joachim


1 Answers

The trick is to make m// work in list context by using a list assignment:

 ($interesting) = $string =~ m/(interesting)/g;

This can be neatly extended to grab more things, eg:

 ($interesting, $alsogood) = $string =~ m/(interesting) boring (alsogood)/g;
like image 173
joachim Avatar answered Oct 06 '22 09:10

joachim