如何编写 Perl 脚本来提取 Perl 包中每个子例程的源代码?
给定一个 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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
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:
首先,您需要找出子例程是由哪个包生成的。 Hack #58 'Find a Subroutine's Source' 中的 Perl Hacks 推荐模块
Sub::识别。
这将打印包裹,子来自。
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
.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
看一下 PPI 模块。
Take a look at the PPI module.