Note that if there is an overall match, each capturing group of the regex will return something to the array even if that particular group was not a part of the overall match:>perl -wMstrict -le "my $s = 'age 23 name john'; my @an = $s =~ m{ age \s+ (\d+) \s+ name \s+ ([a-z]+) }xms; print qq{@an}; " 23 john
The values from unmatched capture groups are undefined and can be detected and filtered:>perl -wMstrict -le "my $s = 'age 23 name john'; my @an = $s =~ m{ name \s+ ([a-z]+) | address \s+ (\d+) }xms; my $captured = join ':', @an; print qq{:$captured:}; " Use of uninitialized value in join or string at -e line 1. :john::
See perlop, the section on Regexp Quote Like Operators, subsection on the m/PATTERN/msixpogc operator, about the seventh paragraph in.>perl -wMstrict -le "my $s = 'age 23 name john'; my @an = $s =~ m{ name \s+ ([a-z]+) | address \s+ (\d+) }xms; defined or $_ = 'UNdefined' for @an; my $captured = join ':', @an; print qq{:$captured:}; " :john:UNdefined:
Note: in Perl 5.10, this can also be done with named capture buffers.
Look for (?<NAME>pattern) in perlre Extended Patterns.
Updates:
In reply to Re: can i get a matched values as an array
by AnomalousMonk
in thread can i get a matched values as an array
by balakrishnan
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |