Vil*_*e M 9 perl metadata metaprogramming
我正在寻找最好,最简单的方法来做类似的事情:
$var1="value";
bunch of code.....
**print allVariablesAndTheirValuesCurrentlyDefined;**
Run Code Online (Sandbox Code Playgroud)
包变量?词汇变量?
可以通过符号表查找包变量.试试Devel :: Symdump:
#!/path/to/perl
use Devel::Symdump;
package example;
$var = "value";
@var = ("value1", "value2");
%var = ("key1" => "value1", "key2" => "value2");
my $obj = Devel::Symdump->new('example');
print $obj->as_string();
Run Code Online (Sandbox Code Playgroud)
词法变量有点小问题,你不会在符号表中找到它们.可以通过属于他们定义的代码块的"暂存器"查找它们.尝试PadWalker:
#!/path/to/perl
use strict;
use warnings;
use Data::Dumper;
use PadWalker qw(peek_my);
my $var = "value";
my @var = ("value1", "value2");
my %var = ("key1" => "value1", "key2" => "value2");
my $hash_ref = peek_my(0);
print Dumper($hash_ref);
Run Code Online (Sandbox Code Playgroud)
该PadWalker模块让你peek_my和peek_our它采取决定来寻找变量,范围LEVEL参数:
The LEVEL argument is interpreted just like the argument to caller.
So peek_my(0) returns a reference to a hash of all the my variables
that are currently in scope; peek_my(1) returns a reference to a hash
of all the my variables that are in scope at the point where the
current sub was called, and so on.
Run Code Online (Sandbox Code Playgroud)
这是一个例子:
#!/usr/bin/perl
use strict;
use warnings;
use PadWalker qw/peek_my/;
my $baz = "hi";
foo();
sub foo {
my $foo = 5;
my $bar = 10;
print "I have access to these variables\n";
my $pad = peek_my(0);
for my $var (keys %$pad) {
print "\t$var\n";
}
print "and the caller has these variables\n";
$pad = peek_my(1);
for my $var (keys %$pad) {
print "\t$var\n";
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5106 次 |
| 最近记录: |