http://www.perlmonks.org?node_id=600483


in reply to How to get ($1, $2, ...)?

Presuming I'm understanding your problem correctly :) I'd do a two step matching process. For this, you'd need additional outer parentheses around each regex for the m//mgc step (in scalar context). Then you could do something like

my $text = <<TEXT; A B 1 2 a b c TEXT my @rxs = ( qr/(\s*(\w)\s+(\w)\s*$)/, qr/(\s*(\d)\s+(\d)\s*$)/, qr/(\s*([a-z])\s+([a-z])\s+([a-z])\s*$)/, ); my @result; for my $rx (@rxs) { if ($text =~ /$rx/mgc) { my $match = $1; # match again to extract submatches my @grps = $match =~ $rx; shift @grps; # remove $1 (outer parens) push @result, [ @grps ]; } } use Data::Dumper; print Dumper \@result;

Prints:

$VAR1 = [ [ 'A', 'B' ], [ '1', '2' ], [ 'a', 'b', 'c' ] ];

Maybe not the best approach performance-wise, but at least reasonably easy to code and maintain...

Alternatively, you could also simply use $& (update: look for the first WARNING: in perldoc perlre for why you might want to avoid $&, $`, $'), i.e.

... my @rxs = ( qr/\s*(\w)\s+(\w)\s*$/, qr/\s*(\d)\s+(\d)\s*$/, qr/\s*([a-z])\s+([a-z])\s+([a-z])\s*$/, ); my @result; for my $rx (@rxs) { if ($text =~ /$rx/mgc) { my $match = $&; # match again to extract submatches my @grps = $match =~ $rx; push @result, [ @grps ]; } }