PadWalker(3) | User Contributed Perl Documentation | PadWalker(3) |
PadWalker - play with other peoples' lexical variables
use PadWalker qw(peek_my peek_our peek_sub closed_over); ...
PadWalker is a module which allows you to inspect (and even change!) lexical variables in any subroutine which called you. It will only show those variables which are in scope at the point of the call.
PadWalker is particularly useful for debugging. It's even used by Perl's built-in debugger. (It can also be used for evil, of course.)
I wouldn't recommend using PadWalker directly in production code, but it's your call. Some of the modules that use PadWalker internally are certainly safe for and useful in production.
"peek_our" works in the same way, except that it lists the "our" variables rather than the "my" variables.
The hash associates each variable name with a reference to its value. The variable names include the sigil, so the variable $x is represented by the string '$x'.
For example:
my $x = 12; my $h = peek_my (0); ${$h->{'$x'}}++; print $x; # prints 13
Or a more complex example:
sub increment_my_x { my $h = peek_my (1); ${$h->{'$x'}}++; } my $x=5; increment_my_x; print $x; # prints 6
my $x = "Hello!"; my $r = peek_sub(sub {$x})->{'$x'}; print "$$r\n"; # prints 'Hello!'
If the sub defines several "my" variables with the same name, you'll get the last one. I don't know of any use for "peek_sub" that isn't broken as a result of this, and it will probably be deprecated in a future version in favour of some alternative interface.
The second argument is a hash of references, much like the one returned from "closed_over".
For example,
my $foo; print var_name(0, \$foo); # prints '$foo' sub my_name { return var_name(1, shift); } print my_name(\$foo); # ditto
Robin Houston <robin@cpan.org>
With contributions from Richard Soberberg, Jesse Luehrs and Yuval Kogman, bug-spotting from Peter Scott, Dave Mitchell and Goro Fuji, and suggestions from demerphq.
Devel::LexAlias, Devel::Caller, Sub::Parameters
Copyright (c) 2000-2009, Robin Houston. All Rights Reserved. This module is free software. It may be used, redistributed and/or modified under the same terms as Perl itself.
2017-11-10 | perl v5.30.2 |