一般的なケースでは実行できません:
my $obj = Obj->new;
my $method = some_external_source();
$obj->$method();
ただし、多数のケースを取得するのはかなり簡単なはずです (このプログラムを自分自身に対して実行します)。
#!/usr/bin/perl
use strict;
use warnings;
sub foo {
bar();
baz(quux());
}
sub bar {
baz();
}
sub baz {
print "foo\n";
}
sub quux {
return 5;
}
my %calls;
while (<>) {
next unless my ($name) = /^sub (\S+)/;
while (<>) {
last if /^}/;
next unless my @funcs = /(\w+)\(/g;
push @{$calls{$name}}, @funcs;
}
}
use Data::Dumper;
print Dumper \%calls;
注、これは見逃します
- 括弧を使用しない関数の呼び出し (例:
print "foo\n";
)
- 逆参照される関数の呼び出し (例:
$coderef->()
)
- 文字列であるメソッドの呼び出し (例:
$obj->$method()
)
- 別の行で開き括弧をパットと呼びます
- 私が考えていない他のこと
間違ってキャッチする
- コメント付き関数 (例:
#foo()
)
- いくつかの文字列 (例
"foo()"
)
- 私が考えていない他のこと
その価値のないハックよりも優れた解決策が必要な場合は、 を調べ始める時が来ましたPPI
が、それでも$obj->$method()
.
退屈だったので、 を使ったバージョンですPPI
。関数呼び出しのみを検索します (メソッド呼び出しではありません)。また、サブルーチンの名前を一意に保つ試みも行いません (つまり、同じサブルーチンを複数回呼び出すと、複数回表示されます)。
#!/usr/bin/perl
use strict;
use warnings;
use PPI;
use Data::Dumper;
use Scalar::Util qw/blessed/;
sub is {
my ($obj, $class) = @_;
return blessed $obj and $obj->isa($class);
}
my $program = PPI::Document->new(shift);
my $subs = $program->find(
sub { $_[1]->isa('PPI::Statement::Sub') and $_[1]->name }
);
die "no subroutines declared?" unless $subs;
for my $sub (@$subs) {
print $sub->name, "\n";
next unless my $function_calls = $sub->find(
sub {
$_[1]->isa('PPI::Statement') and
$_[1]->child(0)->isa("PPI::Token::Word") and
not (
$_[1]->isa("PPI::Statement::Scheduled") or
$_[1]->isa("PPI::Statement::Package") or
$_[1]->isa("PPI::Statement::Include") or
$_[1]->isa("PPI::Statement::Sub") or
$_[1]->isa("PPI::Statement::Variable") or
$_[1]->isa("PPI::Statement::Compound") or
$_[1]->isa("PPI::Statement::Break") or
$_[1]->isa("PPI::Statement::Given") or
$_[1]->isa("PPI::Statement::When")
)
}
);
print map { "\t" . $_->child(0)->content . "\n" } @$function_calls;
}