lexical::underscore - access your caller's lexical underscore
use 5.010; use lexical::underscore; use Test::More; sub is_uppercase { my $var = @_ ? shift : ${lexical::underscore()}; return $var eq uc($var); } my $thing = 'FOO'; my $works = 0; given ( $thing ) { when ( is_uppercase ) { $works++ } } ok($works); done_testing();
Starting with Perl 5.10, it is possible to create a lexical version of the Perl default variable $_. Certain Perl constructs like the given keyword automatically use a lexical $_ rather than the global $_.
$_
given
It is occasionallly useful for a sub to be able to access its caller's $_ variable regardless of whether it was lexical or not. The (_) sub prototype is the official way to do so, however there are sometimes disadvantages to this; in particular it can only appear as the final required argument in a prototype, and there is no way of the sub differentiating between an explicitly passed argument and $_.
(_)
This caused me problems with Scalar::Does, because I wanted to enable the does function to be called as either:
does
does($thing, $role); does($role); # assumes $thing = $_
With _ in the prototype, $_ was passed to the function at the end of its argument list; effectively does($role, $thing), making it impossible to tell which argument was the role.
_
does($role, $thing)
Enter lexical::underscore which allows you to access your caller's lexical $_ variable as easily as:
lexical::underscore
${lexical::underscore()}
You can access lexical $_ further up the call stack using:
${lexical::underscore($level)}
If you happen to ask for $_ at a level where no lexical $_ is available, you get the global $_ instead.
This module does work on Perl 5.8 but as there is no lexical $_, always returns the global $_.
The lexical::underscore function returns a scalar reference to either a lexical $_ variable somewhere up the call stack (using PadWalker magic), or to the global $_ if there was no lexical version.
Wrapping lexical::underscore in ${ ... } dereferences the scalar reference, allowing you to access (and even assign to) it.
${ ... }
Please report any bugs to http://rt.cpan.org/Dist/Display.html?Queue=lexical-underscore.
PadWalker.
Toby Inkster <tobyink@cpan.org>.
This software is copyright (c) 2012, 2014 by Toby Inkster.
This is free software; you can redistribute it and/or modify it under the same terms as the Perl 5 programming language system itself.
THIS PACKAGE IS PROVIDED "AS IS" AND WITHOUT ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.
To install lexical::underscore, copy and paste the appropriate command in to your terminal.
cpanm
cpanm lexical::underscore
CPAN shell
perl -MCPAN -e shell install lexical::underscore
For more information on module installation, please visit the detailed CPAN module installation guide.