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

Given the Perl package Foo.pm for example

package Foo; use strict; sub bar { # some code here } sub baz { # more code here } 1; 

How can I write a script to extract the text source code for each sub, resulting in a hash:

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

I would like to have the text exactly as it appears in the package, spaces and all.

Thanks.

+6
source share
3 answers

PPI is a pain to work with first; the documentation doesn't tell you very well which class documents, which methods are shown in the examples. But it works very 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; 
+16
source

Take a look at the PPI module.

+4
source

First you need to find out from which package the routine came from. The Perl Hacks book in Hack # 58, "Finding the Source of a Subprogram," recommends the Sub::Identify module.

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

This will print the package from which the subprocess comes.

Hack # 55 "Show Source Code on Errors" shows how to get source code based on line numbers (from error messages and warnings). Code examples can be found here: code example

+4
source

Source: https://habr.com/ru/post/891978/


All Articles