Beefy Boxes and Bandwidth Generously Provided by pair Networks
Do you know where your variables are?
 
PerlMonks  

Re^3: Changing every subroutine in many perl scripts

by nitin1704 (Sexton)
on Jul 25, 2012 at 04:17 UTC ( #983542=note: print w/ replies, xml ) Need Help??


in reply to Re^2: Changing every subroutine in many perl scripts
in thread Changing every subroutine in many perl scripts

Okay, I got it now, after going through the CPAN documentation a bit more.

use strict; use warnings; use PPI; my $file = '/path/to/perl/script.pl'; my $Document = PPI::Document->new($file) or die "oops"; for my $sub ( @{ $Document->find('PPI::Statement::Sub') || [] } ) { unless ( $sub->forward ) { my @elements = $sub->children; for ( my $i = 0 ; $i < @elements ; $i++ ) { if ( ref $elements[$i] eq "PPI::Structure::Block" ) { $elements[$i]->start->add_content("my mars code"); } } } } $Document->save($file.".new");


Comment on Re^3: Changing every subroutine in many perl scripts
Download Code
Re^4: Changing every subroutine in many perl scripts
by GrandFather (Sage) on Jul 25, 2012 at 22:24 UTC

    The loop would be better written:

    for my $sub (@{$Document->find('PPI::Statement::Sub') || []}) { next if $sub->forward; for my $child ($sub->children) { if (ref $child eq "PPI::Structure::Block") { $child->start->add_content("my mars code"); } } }

    The next if ... saves a level of indentation and is easier to understand (at least for me) than an unless.

    Using a Perl style for loop in place of the C style for loop is easier to read, easier to understand, more compact and much less likely to get wrong.

    True laziness is hard work

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://983542]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others taking refuge in the Monastery: (8)
As of 2015-07-05 20:20 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    The top three priorities of my open tasks are (in descending order of likelihood to be worked on) ...









    Results (68 votes), past polls