如何编写 Perl 脚本来提取 Perl 包中每个子例程的源代码?

发布于 2024-11-18 10:48:12 字数 404 浏览 6 评论 0原文

给定一个 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 
    }'
};

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

谢谢。

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.

Thanks.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

命硬 2024-11-25 10:48:12

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;

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;
糖果控 2024-11-25 10:48:12

首先,您需要找出子例程是由哪个包生成的。 Hack #58 'Find a Subroutine's Source' 中的 Perl Hacks 推荐模块 Sub::识别。

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

这将打印包裹,子来自。

Hack #55“在错误时显示源代码”展示了如何根据行号(从错误和警告消息)检索源代码。代码示例可以在这里找到:示例代码

First you need to find out, what package the subroutine resulted from. The book Perl Hacks in Hack #58 'Find a Subroutine's Source' recommends module Sub::Identify.

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

This will print the package, the sub is coming from.

Hack #55 'Show Source Code on Errors' shows how to retrieve the source code based on line numbers (from error and warning messages). The code examples can be found here: example code

别忘他 2024-11-25 10:48:12

看一下 PPI 模块。

Take a look at the PPI module.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文