How to replace a (sub's) stub using PPI?
I'm playing with PPI and the problem of fleshing out a stub has me baffled. The following snippet illustrates my problem.
#!/usr/bin/env perl
use if (-d 'C:/Users/clueless_newbie'),lib=>'C:/Users/clueless_newbie/
+GOOGLE~1/code/lib';
use if (-d 'C:/Users/clueless_newbie'),lib=>'C:/Users/clueless_newbie/
+code/Perl-5/devlib';
# $ENV{DBG} -> compile time; $ENV{DEBUG} -> run time.
use if ($ENV{DBG} || $ENV{DEBUG}),"Devel::UnComment","#[=]#","Keep";
use Data::Dumper;
use PPI;
use PPI::Dumper;
use strict;
use warnings;
use 5.10.0;
{ # INTERNALS
}; # INTERNALS
my $raw=<<'__RAW__';
package FeeFi;
sub Fee {
print "Fee\n";
}
sub Fi {
print "Fi\n";
}
-1;
__RAW__
my %sub_h;
{ # Save the subs; replacing them with placeholders
# Create the PPI document
my $document=PPI::Document->new(\$raw)
or die "oops!";
$document->save('before');
for my $sub (@{$document->find('PPI::Statement::Sub') || []}) {
unless ($sub->forward) {
#say $sub->name;
# save the sub and its content
$sub_h{$sub->name}{content}=$sub->content;
# Replace the sub's block as a stub by removing its childr
+en
my @elements=$sub->block->children;
for (my $i=0; $i < @elements; $i++) {
$elements[$i]->remove;
};
};
};
# Save the stubbed out "main/package" under the key '';
$sub_h{''}{content}=$document->content;
};
#=# DEBUG [ sub_h=>\%sub_h ];
# Completing the round trip
{
# Create the stubbed out main
my $document=PPI::Document->new(\$sub_h{''}{content})
or die "oops creating ''!";
#=# DEBUG '',PPI::Dumper->new($document,whitespace=>0)->string;
# Find and flesh out the stubs
for my $stub (@{$document->find('PPI::Statement::Sub') || []}) {
unless ($stub->forward) {
my $name=$stub->name;
#=# TRACE $name;
# Flesh out this stub
my $sub=PPI::Document->new(\$sub_h{$name}{content})->find_
+first('PPI::Statement::Sub');
#=# TRACE '',PPI::Dumper->new($sub,whitespace=>0)->string;
# So ow do I flesh out the stub from $sub????
$stub->insert_after($sub) # <=== Doesn't do it!
or warn "Can't insert_after!";
#=# DEBUG '',PPI::Dumper->new($document,whitespace=>0)->st
+ring;
};
};
#=# DEBUG '',PPI::Dumper->new($document,whitespace=>0)->string;
$document->save('after'); # <=== "after" should be prog
+rammatically equal to "before"
};
exit;