6

I was wondering if there was an operator name for %+, so instead of code like:

/(?<CaptureName>\w+)/;
...
my $whatever=$+{CaptureName};

I could use something more readable:

use English;

/(?<CaptureName>\w+)/;
...
my $whatever=$?????{CaptureName};
Michael Goldshteyn
  • 71,784
  • 24
  • 131
  • 181

3 Answers3

7

Using the English module you can refer to it as %LAST_PAREN_MATCH:

use English;

/(?<CaptureName>\w+)/;
...
my $whatever = $LAST_PAREN_MATCH{CaptureName};
RobEarl
  • 7,862
  • 6
  • 35
  • 50
6

perldoc -v %+

   %LAST_PAREN_MATCH
   %+      Similar to "@+", the "%+" hash allows access to the named capture buffers,
           should they exist, in the last successful match in the currently active
           dynamic scope.
toolic
  • 57,801
  • 17
  • 75
  • 117
6

You can refer to http://perldoc.perl.org/perlvar.html om he future for finding out the symbol names.

In your case the sylbe is called LAST_PAREN_MATCH

%LAST_PAREN_MATCH
%+
Similar to @+ , the %+ hash allows access to the named capture buffers, should they exist, in the last successful match in the currently active dynamic scope.

For example, $+{foo} is equivalent to $1 after the following

The only note I'd make is that the docs includes this:

This variable was added in Perl v5.10.0.

So if you're using an older interpreter this could cause problems.

NOTE as Keith points out int he comment below, you can also use perldoc -v '$+'. This has the benefit of only working if the symbol is available on your installed version of Perl.

chollida
  • 7,834
  • 11
  • 55
  • 85
  • 3
    Or run `perldoc perlvar`, or `perldoc -v '$+'`. Running the `perldoc` command has the advantage that it will show you the documentation for the version of Perl you have on your system, not the one that happens to be documented on the web page. – Keith Thompson Feb 12 '14 at 19:26
  • @KeithThompson, yes Keith that's a good point. Thanks for point it it out. – chollida Feb 12 '14 at 19:29
  • 1
    If you're using it in an older version of Perl, then the lack of the `%+` built-in variable is the least of your worries. **Named captures *don't exist* in Perl prior to 5.10!** (Though in actual fact, the magic hash `%+` does exist in Perl 5.8, 5.6, and probably older versions too. It simply doesn't do anything - it's an unused magic variable. This is an artefact of how the Perl parser works. If there is a magic variable `$x` where x is a punctuation character, then `@x` and `%x` *must* exist, even if they do nothing useful. `$+` exists, and does something useful, therefore `%+` exists.) – tobyink Feb 12 '14 at 21:38