How can I write a Perl script to extract the source code of each subroutine in a Perl package?

痞子三分冷 提交于 2019-11-28 10:20:32

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;

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

Take a look at the PPI module.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!