6

给定一个 Perl 包 Foo.pm,例如

package Foo;

use strict;

sub bar {
    # some code here 
}

sub baz {
    # more code here 
}

1;

如何编写脚本来提取每个子的文本源代码,从而产生哈希:

$VAR1 = {
    'bar' => 'sub bar {
        # some code here 
    }',
    'baz' => 'sub baz {
        # more code here 
    }'
};

我希望文本与包装、空格和所有内容中出现的完全相同。

谢谢。

4

3 回答 3

17

一开始使用 PPI 有点痛苦。该文档并不擅长告诉您哪些类记录了示例中显示的哪些方法。但它工作得很好:

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;
于 2011-07-04T21:31:53.077 回答
5

首先你需要找出子程序是从什么包产生的。Perl Hacks in Hack #58 'Find a Subroutine's Source'这本书推荐了 module Sub::Identify

use Sub::Identify ':all';
print stash_name ( \&YOURSUBROUTINE );

这将打印包,子来自。

技巧 #55 'Show Source Code on Errors' 展示了如何根据行号(来自错误和警告消息)检索源代码。代码示例可以在这里找到:示例代码

于 2011-07-04T19:43:18.560 回答
4

看一下 PPI 模块。

于 2011-07-04T19:40:24.380 回答