Is it possible to store all matches for a regular expression into an array?
I know I can use ($1,...,$n) = m/expr/g;
, but it seems as though that can on
Sometimes you need to get all matches globally, like PHP's preg_match_all
does. If it's your case, then you can write something like:
# a dummy example
my $subject = 'Philip Fry Bender Rodriguez Turanga Leela';
my @matches;
push @matches, [$1, $2] while $subject =~ /(\w+) (\w+)/g;
use Data::Dumper;
print Dumper(\@matches);
It prints
$VAR1 = [
[
'Philip',
'Fry'
],
[
'Bender',
'Rodriguez'
],
[
'Turanga',
'Leela'
]
];