如何编写 Perl 脚本来提取 Perl 包中每个子例程的源代码? [英] How can I write a Perl script to extract the source code of each subroutine in a Perl package?

查看:22
本文介绍了如何编写 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆