In Regexes§
See primary documentation in context for Named captures
Instead of numbering captures, you can also give them names. The generic, and slightly verbose, way of naming captures is like this:
if 'abc' ~~ / = [ \w+ ] /
The square brackets in the above example, which don't usually capture, will now capture its grouping with the given name.
The access to the named capture, $<myname>
, is a shorthand for indexing the match object as a hash, in other words: $/{ 'myname' }
or $/<myname>
.
We can also use parentheses in the above example, but they will work exactly the same as square brackets. The captured group will only be accessible by its name as a key from the match object and not from its position in the list with $/[0]
or $0
.
Named captures can also be nested using regular capture group syntax:
if 'abc-abc-abc' ~~ / =( [ =[abc] ]* % '-' ) /
Coercing the match object to a hash gives you easy programmatic access to all named captures:
if 'count=23' ~~ / =\w+ '=' =\w+ /
A more convenient way to get named captures is by using named regex as discussed in the Subrules section.