发现Perl模块具有的所有子例程的最佳方法是什么? [英] What's the best way to discover all subroutines a Perl module has?
问题描述
以编程方式发现perl模块具有的所有子例程的最佳方法是什么?这可以是模块,类(没有@EXPORT)或两者之间的任何内容.
What's the best way to programatically discover all of the subroutines a perl module has? This could be a module, a class (no @EXPORT), or anything in-between.
以下所有方法看起来都可以使用.我可能会在生产中使用Class :: Sniff或Class :: Inspector.但是,Leon的答案被标记为已接受",因为它可以回答所提出的问题,即使必须使用no strict 'refs'
. :-) Class :: Sniff可能是一个不错的选择,因为它会不断发展;看来已经有很多想法了.
All of the methods below look like they will work. I'd probably use the Class::Sniff or Class::Inspector in production. However, Leon's answer is marked as 'accepted' since it answers the question as posed, even though no strict 'refs'
has to be used. :-) Class::Sniff may be a good choice as it progresses; it looks like a lot of thought has gone into it.
推荐答案
sub list_module {
my $module = shift;
no strict 'refs';
return grep { defined &{"$module\::$_"} } keys %{"$module\::"}
}
ETA:如果要过滤掉导入的子例程,可以执行此操作
ETA: if you want to filter out imported subroutines, you can do this
use B qw/svref_2object/;
sub in_package {
my ($coderef, $package) = @_;
my $cv = svref_2object($coderef);
return if not $cv->isa('B::CV') or $cv->GV->isa('B::SPECIAL');
return $cv->GV->STASH->NAME eq $package;
}
sub list_module {
my $module = shift;
no strict 'refs';
return grep { defined &{"$module\::$_"} and in_package(\&{*$_}, $module) } keys %{"$module\::"}
}
这篇关于发现Perl模块具有的所有子例程的最佳方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!