Search code examples
pythonregexperl

Can I use named groups in a Perl regex to get the results in a hash?


Is it possible to perform a named-group match in Perl's regex syntax as with Python's? I always bind the $n values to proper names after matching, so I'd find it more convenient to do it in the regex itself if it's possible.

Python does it like so:

>>> import re
>>> regex = re.compile(r'(?P<count>\d+)')
>>> match = regex.match('42')
>>> print match.groupdict()
{'count': '42'}

I know the ?P indicates that it's a Python-specific regex feature, but I'm hoping it's in Perl in a different way or was added later on. Is there any way to get a result hash in a similar manner in Perl?


Solution

  • Perl uses (?<NAME>pattern) to specify names captures. You have to use the %+ hash to retrieve them.

    $variable =~ /(?<count>\d+)/;
    print "Count is $+{count}";
    

    This is only supported on Perl 5.10 and higher though.