1lexical::underscore(3)User Contributed Perl Documentationlexical::underscore(3)
2
3
4
6 lexical::underscore - access your caller's lexical underscore
7
9 use 5.010;
10 use lexical::underscore;
11 use Test::More;
12
13 sub is_uppercase {
14 my $var = @_ ? shift : ${lexical::underscore()};
15 return $var eq uc($var);
16 }
17
18 my $thing = 'FOO';
19 my $works = 0;
20
21 given ( $thing ) {
22 when ( is_uppercase ) { $works++ }
23 }
24
25 ok($works);
26 done_testing();
27
29 Starting with Perl 5.10, it is possible to create a lexical version of
30 the Perl default variable $_. Certain Perl constructs like the "given"
31 keyword automatically use a lexical $_ rather than the global $_.
32
33 It is occasionallly useful for a sub to be able to access its caller's
34 $_ variable regardless of whether it was lexical or not. The "(_)" sub
35 prototype is the official way to do so, however there are sometimes
36 disadvantages to this; in particular it can only appear as the final
37 required argument in a prototype, and there is no way of the sub
38 differentiating between an explicitly passed argument and $_.
39
40 This caused me problems with Scalar::Does, because I wanted to enable
41 the "does" function to be called as either:
42
43 does($thing, $role);
44 does($role); # assumes $thing = $_
45
46 With "_" in the prototype, $_ was passed to the function at the end of
47 its argument list; effectively "does($role, $thing)", making it
48 impossible to tell which argument was the role.
49
50 Enter "lexical::underscore" which allows you to access your caller's
51 lexical $_ variable as easily as:
52
53 ${lexical::underscore()}
54
55 You can access lexical $_ further up the call stack using:
56
57 ${lexical::underscore($level)}
58
59 If you happen to ask for $_ at a level where no lexical $_ is
60 available, you get the global $_ instead.
61
62 This module does work on Perl 5.8 but as there is no lexical $_, always
63 returns the global $_.
64
65 Technical Details
66 The "lexical::underscore" function returns a scalar reference to either
67 a lexical $_ variable somewhere up the call stack (using PadWalker
68 magic), or to the global $_ if there was no lexical version.
69
70 Wrapping "lexical::underscore" in "${ ... }" dereferences the scalar
71 reference, allowing you to access (and even assign to) it.
72
74 Please report any bugs to
75 <http://rt.cpan.org/Dist/Display.html?Queue=lexical-underscore>.
76
78 PadWalker.
79
81 Toby Inkster <tobyink@cpan.org>.
82
84 This software is copyright (c) 2012, 2014 by Toby Inkster.
85
86 This is free software; you can redistribute it and/or modify it under
87 the same terms as the Perl 5 programming language system itself.
88
90 THIS PACKAGE IS PROVIDED "AS IS" AND WITHOUT ANY EXPRESS OR IMPLIED
91 WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF
92 MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.
93
94
95
96perl v5.32.1 2021-01-27 lexical::underscore(3)