0

I'm trying to capture named groups in an array.

use strict;
use warnings;
use Data::Dumper;

my $text = 'My aunt is on vacation and eating some apples and banana';
$text =~ m/(?<Letter>A.)/img ;
print Dumper(%-) ;

output is

$VAR1 = 'Letter';
$VAR2 = [
          'au'
        ];

but I would expect or actually was hoping that any occurrence will appear in the array.

$VAR1 = 'Letter';
$VAR2 = [
          'au',
          'ac',
          'at',
          'an',
          'at',
          'an'
        ];

Any chance to get all groups in one array?

1 Answer 1

3

You can either run the m//g in list context to get all the matching substrings (but without the capture names), or you need to match in a loop:

my @matches = $text =~ m/(?<Letter>A.)/img ;
print Dumper(\@matches) ;

or

while ($text =~ m/(?<Letter>A.)/img) {
       print Dumper(\%+) ;
}
Sign up to request clarification or add additional context in comments.

4 Comments

Champion: what a magic in this code +1. How its printing with letter 'Letter' => 'an' Could you please explain the second code?
%- is needed when there are several groups of the same name. %+ is simpler when there's only one group per name. Using a reference (i.e. \) in Dumper for a hash or array prints the structure rather than printing individual values (or keys and values).
But if %- is capturing multiple groups of same name and giving an array for what do I need to run with foreach over it again. Confusing and not logical to me. But thanks for you answer. Will create a function retuning the array I require.
@EricStolz: %- is for cases like /a(?<letter>.).*?a(?<letter>.)/, where the same named capture group appears several times in the regex, not when it matches several times. The latter case must be solved with a loop.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.