in reply to Is there a default array for reg exp memory variables?
The return value of the "=~" operator (if called in list context) is the array you desire.
use Data::Dumper; if (my @r = "foo bar baz" =~ /(foo) (bar) (baz)/) { print Dumper \@r } __END__ $VAR1 = [ 'foo', 'bar', 'baz' ];
You say:
Can we get hold of that array explicitly somehow when we are not in list context?
... so clearly you already know the above. Why not just use list context? There is rarely any reason to explicitly avoid it when regexp matching. Please explain what you're trying to actually do, and why performing matches in list context is insufficient.
Depending on what you're trying to do, you could consider using named captures, which get stored into the hash %-. If you name the captures appropriately, you could assemble them into an array...
sub get_caps () { my @caps; my $i = 1; while (exists $-{'cap'.$i}) { push @caps, $-{'cap'.$i++}->[0]; } @caps; } use Data::Dumper; if (scalar("foo bar baz" =~ /(?<cap1>foo) (?<cap2>bar) (?<cap3>baz)/)) { my @r = get_caps; print Dumper \@r; } __END__ $VAR1 = [ 'foo', 'bar', 'baz' ];
Though obviously that involves modifying the regular expression itself to add the named captures. And it needs a non-archaic version of Perl (at least 5.10).
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: Is there a default array for reg exp memory variables?
by korpenkraxar (Sexton) on Feb 05, 2012 at 23:05 UTC | |
by BrowserUk (Patriarch) on Feb 05, 2012 at 23:11 UTC |