LanX has asked for the wisdom of the Perl Monks concerning the following question:

In continuation of Re^3: Greedy modifier found to be working non-greedy in a named group

I googled and could only find this SO discussion match-positions-of-named-capture-groups-in-perls-regexps but poor Felix didn't get a proper answer.

Though I slightly remember we already had this discussion here...

(something like finding the index of a named capture and accessing @+ / @- probably? Hint: %- doesn't help here)

update

I tried to look into Tie::Hash::NamedCapture , the "Pragmatic Module" used to implement %+ and %- but stopped at the XS barrier

Cheers Rolf
(addicted to the Perl Programming Language :)
Wikisyntax for the Monastery FootballPerl is like chess, only without the dice

Replies are listed 'Best First'.
Re: [RE] match positions of named captures?
by Veltro (Hermit) on Dec 02, 2019 at 15:23 UTC

    The named captures (or resulting hashes) do not have a relation to the actual position of the place where the group is defined. I think the whole intend of the module has a different purpose and I doubt the developer had group position in mind.

    In the example that follows the results in this particular case foo and bar come from two different groups. How do you expect to get a position for that named group?

    use strict ; use warnings ; use Data::Dumper ; my $str = "abcdef" ; $str =~ /(?<foo>[ab])*(?<bar>c)(?<foo>d)(?<bar>[ef]*)/ ; print Dumper(\%-) ;
    $VAR1 = { 'foo' => [ 'b', 'd' ], 'bar' => [ 'c', 'ef' ] };
      > How do you expect to get a position for that named group?

      by associating a named capture to an capture index. The word tie implies that this is done somewhere.

      $VAR1 = { 'foo' => [ 'b', # $1 'd' # $3 ], 'bar' => [ 'c', # $2 'ef' # $4 ] };

      Cheers Rolf
      (addicted to the Perl Programming Language :)
      Wikisyntax for the Monastery FootballPerl is like chess, only without the dice

Re: [RE] match positions of named captures?
by haukex (Archbishop) on Dec 02, 2019 at 18:30 UTC
    I tried to look into Tie::Hash::NamedCapture, the "Pragmatic Module" used to implement %+ and %- but stopped at the XS barrier

    I looked at this as well, specifically at FIRSTKEY and NEXTKEY in NamedCapture.xs, because I was hoping that maybe the iteration order would be the same as the order of the capture groups, but sadly that doesn't seem to be the case. Anyway, its implementation appears to use named_buff_iter in regcomp.c, and the central function here appears to be reg_named_buff_nextkey. But that's as far as I've gotten in my research, my understanding of the internals isn't good enough to see if there's an "easy" way to access the capture group name to number mapping.

Re: [RE] match positions of named captures?
by QM (Parson) on Dec 02, 2019 at 12:19 UTC
    I assume you've had a good read of the perlre doc, especially Capture Groups?

    -QM
    --
    Quantum Mechanics: The dreams stuff is made of