http://www.perlmonks.org?node_id=850073

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

Given a package name, is it possible to somehow get a list of all the subs that exist within that package?

I know I can check for a given sub like this
$sub = $obj->can("print");
but what I'd like is something like
@subnames = $obj->can(); # Just to illustrate, does not work
or even
@subnames = Some::Class::can(); # Just to illustrate, does not work

-- Time flies when you don't know what you're doing

Replies are listed 'Best First'.
Re: Package introspection
by jau (Hermit) on Jul 17, 2010 at 11:17 UTC

    You could use Class::Inspector, for example.

    $function_names = Class::Inspector->functions( 'My::Class' );

    Or:

    $method_names = Class::Inspector->methods( 'My::Class' );
      Exactly what I was looking for, thank you :-D

      -- Time flies when you don't know what you're doing
Re: Package introspection
by JavaFan (Canon) on Jul 17, 2010 at 09:51 UTC
    @subnames = grep {Test->can($_)} keys %Test::;
    Although that gets tricky (both false positives and false negatives) in the face of inheritance. (But then, so does your use of can).
Re: Package introspection
by chromatic (Archbishop) on Jul 17, 2010 at 22:14 UTC

    In Moose this is something like:

    my @methods = $obj->meta->get_all_methods();
Re: Package introspection
by morgon (Priest) on Jul 18, 2010 at 07:10 UTC
    You can also check the symbol table (you won't get any inherited methods then, which may or may not be what you want).

    For a package "Hubba", the symbol table can be found in %Hubba:: (the keys of this hash are the symbols) and the subroutines are in the CODE-slot.

    So you find all subs defined in a package $package you can simply grep for all symbols that have a defined CODE-slot like this ugly hack:

    my @sub_names = grep { defined *{"${package}::$_"}{CODE} } keys %{"${p +ackage}::"}
      I'll use Class::Inspector for now as it looks a lot cleaner, but this is good to know and I bet this is exactly how that class works too.

      -- Time flies when you don't know what you're doing
Re: Package introspection
by exussum0 (Vicar) on Jul 18, 2010 at 11:34 UTC
    Class::Mop is my hammer now-a-days.