Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I list available methods on a given object or package in Perl?

How do I list available methods on a given object or package in Perl?

like image 374
Benoît Avatar asked May 26 '09 12:05

Benoît


3 Answers

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

my $methods =   Class::Inspector->methods( 'Foo::Class', 'full', 'public' ); 
like image 50
Nic Gibson Avatar answered Sep 21 '22 10:09

Nic Gibson


If you have a package called Foo, this should 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 methods in package Foo:

no strict 'refs'; my @methods = grep { defined &{"Foo::$_"} } keys %Foo::; use strict 'refs'; 
like image 31
Chris Lutz Avatar answered Sep 22 '22 10:09

Chris Lutz


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

print PackageNameHere->meta->dump;

And for more complete data:

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

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

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

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

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

For starters:

 $meta->get_method_map(); 

use Moose; #, its awesome.

like image 26
Kent Fredric Avatar answered Sep 22 '22 10:09

Kent Fredric