[ACCEPTED]-How do I list available methods on a given object or package in Perl?-introspection

Accepted answer
Score: 40

There are (rather too) many ways to do this 6 in Perl because there are so many ways to 5 do things in Perl. As someone commented, autoloaded 4 methods will always be a bit tricky. However, rather 3 than rolling your own approach I would suggest 2 that you take a look at Class::Inspector on CPAN. That will 1 let you do something like:

my $methods =   Class::Inspector->methods( 'Foo::Class', 'full', 'public' );
Score: 24

If you have a package called Foo, this should 2 do it:

no strict 'refs';
for(keys %Foo::) { # All the symbols in Foo's symbol table
  print "$_\n" if exists &{"Foo::$_"}; # check if symbol is method
}
use strict 'refs';

Alternatively, to get a list of all 1 methods in package Foo:

no strict 'refs';
my @methods = grep { defined &{"Foo::$_"} } keys %Foo::;
use strict 'refs';
Score: 13

if you have a package that is using Moose its 8 reasonably simple:

print PackageNameHere->meta->dump;

And for more complete 7 data:

use Data::Dumper;
print Dumper( PackageNameHere->meta ); 

Will get you started. For everything 6 else, theres the methods that appear on 5 ->meta that are documented in Class::MOP::Class

You can do a bit 4 of AdHoc faking of moose goodness for packages 3 without it with:

use Class::MOP::Class;
my $meta = Class::MOP::Class->initialize( PackageNameHere );

and then proceed to use 2 the Class::MOP methods like you would with 1 Moose.

For starters:

 $meta->get_method_map(); 

use Moose; #, its awesome.

Score: 3

In general, you can't do this with a dynamic 8 language like Perl. The package might define 7 some methods that you can find, but it can 6 also make up methods on the fly that don't 5 have definitions until you use them. Additionally, even 4 calling a method (that works) might not 3 define it. That's the sort of things that 2 make dynamic languages nice. :)

What task 1 are you trying to solve?

Score: 1

A good answer from How to get structure and inheritance history
The classes from which 2 an object's class currently inherits can 1 be found using the following:

use mro          qw( );
use Scalar::Util qw( blessed );
say join ", ", @{ mro::get_linear_isa(blessed($o)) };

More Related questions