in reply to Is there a default array for reg exp memory variables?
korpenkraxar: As others have pointed out and as you have already acknowledged, assigning captures to your own array or using named captures is probably the way to go, especially since you already know the capture groups $1 $2 $3 $n that are present in the regex because you wrote the regex yourself!
In case you are dealing with a foreign regex, here's a trick to let you know the highest capture group present in the regex based on the @- special variable (see perlvar). (Update: Note: The presence of a capture group in a regex does not mean it captured anything meaningful or that it matched at all.)
>perl -wMstrict -le "my $s = 'Fu Feet Fie Foe Fum'; my $f = qr{ F \w* }xms; for my $rx ( qr{ (X) }xms, qr{ ($f) \s* ($f) }xms, qr{ ($f) \s* ($f) \s* ($f) }xms, qr{ ($f) \s* ($f) \s* ($f) \s* ($f) }xms, ) { $s =~ $rx; print qq{highest capture group is $#-, captures are}; printf qq{\$$_->[0] eq '$_->[1]' } for map [ $_, eval qq{\$$_} ], 1 .. $#-; print qq{\n}; } " highest capture group is -1, captures are highest capture group is 2, captures are $1 eq 'Fu' $2 eq 'Feet' highest capture group is 3, captures are $1 eq 'Fu' $2 eq 'Feet' $3 eq 'Fie' highest capture group is 4, captures are $1 eq 'Fu' $2 eq 'Feet' $3 eq 'Fie' $4 eq 'Foe'
Update: Changed example code: added no-match case.
|
|---|