如何编写Perl脚本以提取Perl包中每个子例程的源代码? [英] How can I write a Perl script to extract the source code of each subroutine in a Perl package?
本文介绍了如何编写Perl脚本以提取Perl包中每个子例程的源代码?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
给出一个Perl软件包Foo.pm,例如
Given a Perl package Foo.pm, e.g.
package Foo;
use strict;
sub bar {
# some code here
}
sub baz {
# more code here
}
1;
我该如何编写脚本以提取每个子程序的文本源代码,从而导致散列:
How can I write a script to extract the textual source code for each sub, resulting in a hash:
$VAR1 = {
'bar' => 'sub bar {
# some code here
}',
'baz' => 'sub baz {
# more code here
}'
};
我希望文本与包装,空格以及所有内容完全相同.
I'd like to have the text exactly as it appears in the package, whitespace and all.
谢谢.
推荐答案
PPI刚开始使用时有点痛苦.该文档并不擅长告诉您哪些类记录了示例中显示的哪些方法.但是效果很好:
PPI is kind of a pain to work with at the very first; the documentation is not good at telling you which class documents which methods shown in the examples. But it works pretty well:
use strict;
use warnings;
use PPI;
my %sub;
my $Document = PPI::Document->new($ARGV[0]) or die "oops";
for my $sub ( @{ $Document->find('PPI::Statement::Sub') || [] } ) {
unless ( $sub->forward ) {
$sub{ $sub->name } = $sub->content;
}
}
use Data::Dumper;
print Dumper \%sub;
这篇关于如何编写Perl脚本以提取Perl包中每个子例程的源代码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文