Beefy Boxes and Bandwidth Generously Provided by pair Networks
Keep It Simple, Stupid
 
PerlMonks  

Re: How to get ($1, $2, ...)?

by almut (Canon)
on Feb 16, 2007 at 17:28 UTC ( #600483=note: print w/replies, xml ) Need Help??


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 ]; } }

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://600483]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others examining the Monastery: (7)
As of 2019-07-17 13:14 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found

    Notices?