eod has asked for the wisdom of the Perl Monks concerning the following question:

Hi all,

Imaging you get the name of a package in a variable:
my $package = "MyPackage";

and you want to access the symbol table of that package, something like:
foreach my $sym (keys %$package::){ print "$syn\n"; }
What is the way to do that?

thanks!

Replies are listed 'Best First'.
Re: look up the symbol table of a variable
by brian_d_foy (Abbot) on Apr 24, 2005 at 21:03 UTC

    Devel::Symdump makes this rather easy.

    --
    brian d foy <brian@stonehenge.com>
Re: look up the symbol table of a variable
by tlm (Prior) on Apr 24, 2005 at 20:47 UTC

    Try this:

    my $package = "MyPackage"; { no strict 'refs'; for my $sym ( keys %{ "${package}::" } ) { print "$sym\n"; } }
    The above makes use of a symbolic reference (the string "MyPackage::"), therefore, I turn off strict "refs" in the enclosing block. In the call to keys it is necessary to enclose "package" in curlies, otherwise perl will think you are talking about the package variable $package:: (no pun intended) which is distinct from the lexical $package.

    the lowliest monk

Re: look up the symbol table of a variable
by BUU (Prior) on Apr 24, 2005 at 20:23 UTC
    %{ $::{ "${package}::" } }

      When I try:

      use strict; use Foo::Bar; my $package = 'Foo::Bar'; for my $sym ( keys %{ $::{ "${package}::" } } ) { print "$sym\n"; }
      ...I get no output, but with this I do:
      use strict; use Foo::Bar; my $package = 'Foo::Bar'; { no strict q(refs); for my $sym ( keys %{ "${package}::" } ) { print "$sym\n"; } } __END__ PI import
      For both, Foo/Bar.pm is
      package Foo::Bar; $PI = 3.14; __END__

      Update: Simplified code a bit.

      the lowliest monk

        Yes, I think you are correct. (See the 2nd update in my previous reply.)
        chas
Re: look up the symbol table of a variable
by chas (Priest) on Apr 24, 2005 at 20:50 UTC
    For example, for main:
    foreach my $name (sort keys %{*main::}){ print "Symbol '$name'\n"; }
    chas
    (Update: Using BUU's construction if the name is in a variable.
    Update 2: That construction seemed fine when $package="main", but doesn't seem right for cases such as $package="HTML::Parser", when the :: appears. For such cases, tlm's construction seems to give the desired result.)
Re: look up the symbol table of a variable
by zentara (Cardinal) on Apr 25, 2005 at 11:04 UTC
    And here is a simple example with Devel::SymDump.
    use Devel::Symdump; use CGI; my $obj = Devel::Symdump->new('CGI'); print $obj->as_string;

    I'm not really a human, but I play one on earth. flash japh