in reply to better way to get last named capture group
perl -E 'say "xxx" =~ s/^.(?{"a"})|.$(?{"c"})|.(?{"b"})/$^R/gr'
or with /x
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")say "xxx" =~ s/ ^. (?{ "a" }) | .$ (?{ "c" }) | . (?{ "b" }) /$^R/grx'
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 |