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

I have a module that creates a bunch of constant values which I can refer to elsewhere in my application along the line of if($foo eq ALWAYS)... for documentation sake I would like to have a little script that loads the module and prints all the constants and their values. I have several installations with the module in place, so I really don't want to do it in the module itself. Just a few liner to dump the constant name and its values, but I can't figure out what to do after use strict; can anybody give me a decent push?

g_White

Replies are listed 'Best First'.
Re: Listing all Constants and values
by broquaint (Abbot) on Oct 11, 2003 at 00:30 UTC
    If you're using the constant package then you could just look at the %constant::declared hash e.g
    require Your::Module; my $pkg = 'Your::Module'; for(grep /^$pkg\::/, keys %constant::declared) { my($name) = /::(\w+)$/; my $val = $pkg->can($name)->(); print "$name: $val\n"; }
    So there we just look for the constants that have been declared in Your::Module, grab the constant name, execute the constant sub of that name for the value, and then print them both out.
    HTH

    _________
    broquaint

Re: Listing all Constants and values
by Zaxo (Archbishop) on Oct 10, 2003 at 23:59 UTC

    The Devel namespace has lots of modules you can use for this sort of thing. You can, however, get some information on your own from the symbol table. Here is a simple illustration of that sort of thing from the command line,

    $ perl -e'BEGIN{@ns{keys %::} = ()}; $foo = "bar";@names = grep {!exis +ts $ns{$_}} keys %::; print "@names",$/' foo names $
    The BEGIN block collects all the keys of %main:: which exist before other stashes are formed and uses them as keys in the %ns hash. That hash is used to eliminate the 'noise' leaving only the names you have defined since.

    That could be carried further by checking names against properties by the likes of,

    print "foo has: ", $_, $" for (grep {*foo{$_} qw/SCALAR ARRAY HASH CODE GLOB IO/;
    The values may be examined by dereferencing. Again the command line,
    $ perl -e'BEGIN{@ns{keys %::} = ()}; $foo = "bar";@names = grep {!exis +ts $ns{$_}} keys %::; print ${*foo{SCALAR}} ,$/' bar $
    All this only addresses the symbol tables. Lexical variables are not accessible by this method.

    After Compline,
    Zaxo

Re: Listing all Constants and values
by chromatic (Archbishop) on Oct 10, 2003 at 23:59 UTC