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

Hi monks, i have written a small script to remove and add comments in a file, problem comes here is:removing comments is working but adding comments is not working, if i will run the same code separately (through command line , manually) working fine , can any one help me.

My input file test.txt consists test test test\n testing testing\n test\n testing\n

!/usr/bin/perl -w use strict; use warnings; my $cmd; my $cmd1; $cmd = system("perl -pi -e 's/#//' test.txt"); # removing comments wor +king $cmd1 = system("perl -pi -e 's/(?=.*\btest\b)/#/' test.txt"); #Adding +#'s is not working print "$cmd \n"; print "$cmd1\n";

Replies are listed 'Best First'.
Re: System command problem in perl
by jwkrahn (Abbot) on Nov 26, 2010 at 15:19 UTC

    You don't need to run perl through system, you can do that directly in perl:

    #!/usr/bin/perl use strict; use warnings; { local ( $^I, @ARGV ) = ( '', 'test.txt' ); while ( <> ) { s/#//; print; } } { local ( $^I, @ARGV ) = ( '', 'test.txt' ); while ( <> ) { s/(?=.*\btest\b)/#/; print; } }
Re: System command problem in perl
by mjscott2702 (Pilgrim) on Nov 26, 2010 at 12:50 UTC
    That shouldn't even compile/run:
    Global symbol "$cmd1" requires explicit package name at try4.pl line 3.
    Global symbol "$cmd1" requires explicit package name at try4.pl line 4.
    Global symbol "$cmd" requires explicit package name at try4.pl line 5.
    Global symbol "$cmd1" requires explicit package name at try4.pl line 6.
    
    Apart from not using "my" to declare your variables, notice that you reference $cmd, which isn't actuallly declared/assigned to anywhere.
Re: System command problem in perl
by Anonymous Monk on Nov 26, 2010 at 12:01 UTC
    1) don't use the shell
    my @args = ( $^X, qw' -pi -e ', $perlprogram, 'test.txt' ); system {$args[0]} @args;

    2) What is your expected output? Where do you want to add # that isn't happening

      system {$args[0]} @args;

      No, don't use system just to run perl when the task can be simply done in a single Perl script. See jwkrahn's response below.