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

I could swear that I have seen this done before, but how do I traverse all the variables in a namespace using a loop?

Replies are listed 'Best First'.
Re: Traversing variables in a namespace
by btrott (Parson) on Feb 05, 2001 at 23:13 UTC
    Take a look at Devel::Symdump.

    Example code:

    my $sym = Devel::Symdump->new('Foo'); my @scalars = $sym->scalars; for my $s (@scalars) { # do something }
    Or you could roll your own:
    my $class = 'Foo'; while (my($key, $val) = each %{"${class}::"}) { local(*ENTRY) = $val; # $key is the name of the symbol table entry, # and *ENTRY is the value--the glob. You can, # for example, look at *ENTRY{CODE} to see # if there's a sub called $key. }
Re: Traversing variables in a namespace
by jeroenes (Priest) on Feb 05, 2001 at 23:03 UTC
    You can get the names of the variables from main with '%::'. I use eval to extract the values:
    for $name (keys %::) { eval 'my $val = '.$name.';'; }
    Hope this helps,

    Jeroen
    "We are not alone"(FZ)

      Using eval is overkill in this case. It is more efficient and probably more straightforward to disable strict 'refs' and use symbolic reference to extract a variable's value from the symbol table:
      for $name (keys %::) { no strict 'refs'; $val = $$name; }
         MeowChow                                               
                      print $/='"',(`$^X\144oc $^X\146aq1`)[-2]
        If you remember that %main:: is a hash of globs, then a simple derefence works, doesn't worry strict and allows you to get all types of vars. But you may only want scalars, and not a scalar version of almost everything.
        for (keys %main::) { $val = ${ *{ $main::{$_} }{SCALAR} }; }
Re: Traversing variables in a namespace
by MeowChow (Vicar) on Feb 06, 2001 at 00:43 UTC
    There's a fairly good treatment of this issue on page 281 of the Camel book.
Re: Traversing variables in a namespace
by Yoda (Sexton) on Feb 06, 2001 at 09:32 UTC
    Advanced Perl Programming is a good place to look. Chapter 6 on Modules has a section "Accessing the symbol table". I can't remember if it is Chapter 6 or 7, but there is even a neat little example program.