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

Hi All,
  I've got a module that creates some routines named routinecategory_NAME, with NAME being swapped for the routine name.
At a later stage I'm populating a selection box with the various NAME's. At the moment I'm reading the module in as a file and extracting the names with REGEXP. Something tells me there is a quicker and better way of doing it.

Help please?

Replies are listed 'Best First'.
Re: Getting a list of sub routines
by friedo (Prior) on Jun 24, 2005 at 00:38 UTC
    You could grep them out of the symbol table:

    my @subs = grep { defined &{ $_ } } keys %Your::Package::;

    Update: I probably should have also mentioned that if you're doing this from a different package, you'll need to prepend the package name to make sure you're checking for defined-ness in the right symbol table. E.g.

    package Foo; sub foo { } sub bar { } sub baz { } package Bar; my @subs = grep { defined &{ "Foo::$_" } } keys %Foo::; print join "\n", @subs;
Re: Getting a list of sub routines
by adrianh (Chancellor) on Jun 24, 2005 at 01:07 UTC
    use Devel::Symdump; my @names = map { $_ =~ /routinecategory_(.*)/s ? $1 : () } Devel::Symdump->new( 'MyPackage' )->functions;
Re: Getting a list of sub routines
by davidrw (Prior) on Jun 24, 2005 at 01:22 UTC
    Can you have the module keep track of the NAME's so that a getNAMEs() just returns the list? If the routines are static in there, this could just be a hardcoded list (or maybe one that's populated in BEGIN by one of the above methods). If these (as i assume they are from OP) subroutines are created at runtime, the creation code could just push the NAME onto an internal list, which is what your new getNAMEs() subroutine would return.
Re: Getting a list of sub routines
by izut (Chaplain) on Jun 24, 2005 at 11:09 UTC
Re: Getting a list of sub routines
by mrpeabody (Friar) on Jun 24, 2005 at 06:56 UTC
    Store the functions in a hash with their names as the keys.

    Solves scoping issues, keeps everything in one place, easy to extend, won't mysteriously break if you reformat the source.