How can I list all variables that are in a given scope?

后端 未结 4 1212
半阙折子戏
半阙折子戏 2020-12-08 10:05

I know I can list all of the package and lexcial variables in a given scope using Padwalker\'s peek_our and peek_my, but how can I get the names an

4条回答
  •  春和景丽
    2020-12-08 10:23

    You can access the symbol table, check out p. 293 of "Programming Perl" Also look at "Mastering Perl: http://www252.pair.com/comdog/mastering_perl/ Specifically: http://www252.pair.com/comdog/mastering_perl/Chapters/08.symbol_tables.html

    Those variables you are looking for will be under the main namespace

    A quick Google search gave me:

    {
        no strict 'refs';
    
        foreach my $entry ( keys %main:: )
        {
            print "$entry\n";
        }
    }
    

    You can also do

    *sym = $main::{"/"}
    

    and likewise for other values

    If you want to find the type of the symbol you can do (from mastering perl):

    foreach my $entry ( keys %main:: )
    {
        print "-" x 30, "Name: $entry\n";
    
        print "\tscalar is defined\n" if defined ${$entry};
        print "\tarray  is defined\n" if defined @{$entry};
        print "\thash   is defined\n" if defined %{$entry};
        print "\tsub    is defined\n" if defined &{$entry};
    }
    

提交回复
热议问题