TheGNUGuy TheGNUGuy - 1 year ago 65
Perl Question

How can I store regex captures in an array in Perl?

I'm trying to use regex in Perl. What I was wonder was if it is possible to store all matches to the expression into an array? I know I can use the following:

($1,...,$n) = m/expr/g;
but it seems as though that can only be used if you know the number of matches you are looking for. I have tried
my @array = m/expr/g;
but that doesn't seem to work.

Thanks for your help!

Answer Source

If you're doing a global match (/g) then the regex in list context will return all of the captured matches. Simply do:

my @matches = ( $str =~ /pa(tt)ern/g )

This command for example:

perl -le '@m = ( "foo12gfd2bgbg654" =~ /(\d+)/g ); print for @m'

Gives the output:

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download