What’s the best way to discover all variables a Perl application has currently defined?

前端 未结 5 1992
太阳男子
太阳男子 2020-12-30 11:01

I am looking for best, easiest way to do something like:

$var1=\"value\";
bunch of code.....
**print allVariablesAndTheirValuesCurrentlyDefined;**

5条回答
  •  执念已碎
    2020-12-30 11:28

    The PadWalker module gives you peek_my and peek_our which take a LEVEL argument that determines which scope to look for variables in:

    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.
    

    Here is an example:

    #!/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";
        }
    }
    

提交回复
热议问题