发现Perl应用程序当前定义的所有变量的最佳方法是什么?

Vil*_*e M 9 perl metadata metaprogramming

我正在寻找最好,最简单的方法来做类似的事情:

$var1="value";
bunch of code.....
**print allVariablesAndTheirValuesCurrentlyDefined;**
Run Code Online (Sandbox Code Playgroud)

Mar*_*son 9

包变量?词汇变量?

可以通过符号表查找包变量.试试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)


Nat*_*hen 7

全局符号表是%main::,因此您可以从那里获取全局变量.但是,每个条目都是一个typeglob,它可以包含多个值,例如$ x,@ x,%x等,因此您需要检查每种数据类型.你可以在这里找到执行此操作的代码.该页面上的注释可能有助于您找到非全局变量的其他解决方案(例如使用"my"声明的词法变量).


Cha*_*ens 6

PadWalker模块让你peek_mypeek_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)