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

Dear monks!
I have encountered a silly problem while trying to write simple one liner.
I seem to not be able to skip one line when using '-p' command line switch.
This is what I have tried so far:
perl -pl -e 'next if /bala/;s/([^:]+)([^:]+)/$2$1/' file.txt

If I switch 'next' to 'last' it stops the loop properly.
The questions is in what place I made a mistake, and how to correct it, so the loop skips one line?
Is the '-n' switch with 'print' the only way?
Thanks for any tips!

Lost-in-perl

Replies are listed 'Best First'.
Re: perl -pl with next?
by PodMaster (Abbot) on Jan 27, 2005 at 08:56 UTC
    C:\>perl -MO=Deparse -pl -e "next if /bala/;s/([^:]+)([^:]+)/$2$1/" fi +le.txt BEGIN { $/ = "\n"; $\ = "\n"; } LINE: while (defined($_ = <ARGV>)) { chomp $_; next if /bala/; s/([^:]+)([^:]+)/$2$1/; } continue { print $_; } -e syntax OK
    See that continue in there (also documented in perlrun)? Know what it does? You should try goto LINE.

    MJD says "you can't just make shit up and expect the computer to know what you mean, retardo!"
    I run a Win32 PPM repository for perl 5.6.x and 5.8.x -- I take requests (README).
    ** The third rule of perl club is a statement of fact: pod is sexy.

Re: perl -pl with next?
by jmcnamara (Monsignor) on Jan 27, 2005 at 09:03 UTC

    I'd use -n in this case. Otherwise you could use the slightly obscure goto LINE:
    perl -ple 'goto LINE if /bala/; s/([^:]+)([^:]+)/$2$1/' file.txt f +ile.txt

    --
    John.

Re: perl -pl with next?
by deibyz (Hermit) on Jan 27, 2005 at 09:01 UTC
    From perldoc perlrun:

    -p causes Perl to assume the following loop around your program, which makes it iterate over filename arguments somewhat like sed: LINE: while (<>) { ... # your program goes here } continue { print or die "-p destination: $!\n"; }

    So the next statement makes continue block executed. I think -n with explicit print is the better solution. Or maybe you can try a $_="" (untested, just a thought).

      Or maybe you can try a $_="" (untested, just a thought).

      Due to the presence of the -l flag, that will still print a newline. The -n solution works fine though.

      Hugo

        Good catch++

        Too early here in Spain to notice a little -l :( .

        I think I need more coffee.

Re: perl -pl with next?
by holli (Abbot) on Jan 27, 2005 at 09:01 UTC
    IŽd write that as
    perl -n -e 's/([^:]+)([^:]+)/$2$1/, print unless /bala/;' file.txt

    holli, regexed monk