in reply to better way to get last named capture group

I don't believe that specific feature exists, but perl has a lot of other quirky tools in the regex engine, and you haven't really explained what real problem you're trying to solve. At a glance, I can't think how knowing "lastgroup" would be useful in real-world problems, except in the case where you were trying to discover which of N capture groups were found. If the goal was to perform a more efficient "switch" to execute code after specific captures were detected, the perl tool for that is to embed perl code directly into the regex so that it runs right after the capture.
perl -E 'say "xxx" =~ s/^.(?{"a"})|.$(?{"c"})|.(?{"b"})/$^R/gr'

or with /x

say "xxx" =~ s/ ^. (?{ "a" }) | .$ (?{ "c" }) | . (?{ "b" }) /$^R/grx'
The advantage here is that you don't have to re-dispatch based on which matched; you are immediately running code based on the pattern. The disadvantage is that you have to pay close attention to how this feature interacts with backtracking, because the perl regex engine may run your code block before deciding that the pattern doesn't match, and then run different code for the same characters. In this case, I put all the code to execute *after* the pattern has been matched. In general, try to avoid side effects and return a value (to $^R) that can be used only once the replacement is determined to have succeeded. If you need side effects, you can also make use of the various regex directives that prevent backtracking. (see perldoc re and search for "backtrack")

I can dig up examples of how you can expand this to a full language parser, if you're interested.

Replies are listed 'Best First'.
Re^2: better way to get last named capture group
by ysth (Canon) on Jul 01, 2025 at 20:32 UTC