Beefy Boxes and Bandwidth Generously Provided by pair Networks
more useful options

perl in line editing help

by ghosh123 (Monk)
on Aug 27, 2013 at 11:23 UTC ( #1051119=perlquestion: print w/replies, xml ) Need Help??

ghosh123 has asked for the wisdom of the Perl Monks concerning the following question:

Hi ,
In my perl file, I want the print statements to happen only if a ENV variable is set to 1. So I want to to edit all the print statements (dumping to a file)which are there in my file.

My print statements look like :

print FP "this is name",$self->{name}, "\n";
print FP "this is second line\n";

I am trying with the following command but it is not working,
perl -i.bak -p -e s/^print(.*);$/print$1\sif$ENV{DEBUG};/g my_perl_file

Replies are listed 'Best First'.
Re: perl in line editing help
by Corion (Patriarch) on Aug 27, 2013 at 11:27 UTC

    Have you thought about simply changing print to a subroutine call instead?

    sub status { if( $ENV{DEBUG}) { print "@_"; }; }; status( "this is name",$self->{name},"\n" );

    Also see Log::Log4Perl.

    Also, you might want to learn to use your text editor. Most text editors can do various forms of search and replace.

Re: perl in line editing help
by Eily (Monsignor) on Aug 27, 2013 at 12:20 UTC

    The second half of a substitution is not a regex, it's a double quotish context, so \s doesn't mean "a space character" (and even if it did \s stands for a lot of different blank chars, not just one) so you want to put a litteral space here. You'll have to put quotes around your code (or it will be broken into several arguments).

    And, since it is a double quotish context $ENV{DEBUG} will be replaced straightaway, and you will end up with its value in your code. You should escape the $.

    And last thing I saw: unless you use no indentation at all, the print probably isn't the first thing on the line. So you want to allow spaces in front of it. And you probably don't want your code to work on subs that have a name that starts by print, like printfoo

    So, with those corrections, you would have: s/^\s+print\b(.*);$/print$1 if \$ENV{DEBUG};/g

    Now, that's why it didn't work, but Corion's proposition is a far better idea. You'll avoid adding another modifier to a line that already has one. For exemple print $object->method() if ref $object eq 'Class'; would become print $object->method() if ref $object eq 'Class' if $ENV{DEBUG};, which is a syntax error.

Log In?

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://1051119]
Approved by hdb
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others making s'mores by the fire in the courtyard of the Monastery: (4)
As of 2022-05-17 17:38 GMT
Find Nodes?
    Voting Booth?
    Do you prefer to work remotely?

    Results (68 votes). Check out past polls.