Is there a name for the special variable %+?
Asked Answered
L

3

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};
Leoni answered 12/2, 2014 at 19:16 Comment(0)
R
7

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

use English;

/(?<CaptureName>\w+)/;
...
my $whatever = $LAST_PAREN_MATCH{CaptureName};
Ribeiro answered 12/2, 2014 at 19:20 Comment(0)
P
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.
Paulinapauline answered 12/2, 2014 at 19:21 Comment(0)
Y
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.

Ypsilanti answered 12/2, 2014 at 19:22 Comment(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.Toluate
@KeithThompson, yes Keith that's a good point. Thanks for point it it out.Ypsilanti
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.)Prissie

© 2022 - 2024 — McMap. All rights reserved.