Beefy Boxes and Bandwidth Generously Provided by pair Networks chromatic writing perl on a camel
more useful options
 
PerlMonks  

Re: Uncommon* but Useful Perl Command Line Options for One-liners

by sfink (Deacon)
on Jan 29, 2004 at 12:50 UTC ( [id://324988]=note: print w/replies, xml ) Need Help??

This is an archived low-energy page for bots and other anonmyous visitors. Please sign up if you are a human and want to interact.


in reply to Uncommon* but Useful Perl Command Line Options for One-liners

Ok I lied, there is a difference between the longhand perl while (<>) { } statement and -n: you can't use next or last to exit the loop - however you can use BEGIN{ } and END { } blocks to get pre and post loop code, run a text file containing some numbers through this baby:
perl -l -n -e 'BEGIN{$sum=0;} $sum=$sum+ $1 if /(\d+)/;print $1; END { +print "Total: ",$sum}'
You were right the first time. There really is no difference. Why don't next and last work for you?
echo -e "a\nb\nc" | perl -lne 'next if /b/; print' a c echo -e "a\nb\nc" | perl -lne 'last if /b/; print' a
In fact, it is equivalent to LINE: while (defined($_=<ARGV>)) { ... } which means that you can do next LINE if you have a loop within your one-liner.

Two other comments: I use the canonical

perl -lne 'print $s += $1 if /(\d+)/'
for summing numbers. For one-liners, it's much less typing, and gives you pretty much everything you need: the total sum, and a running sum that still allows you to catch errors.

And finally, the one big missing piece in this tutorial is that it is absolutely necessary, for reasons of tradition, to at least try to make your options spell out words. So never use -alne when -lane would work.

Replies are listed 'Best First'.
Re: Re: Uncommon* but Useful Perl Command Line Options for One-liners
by demerphq (Chancellor) on Apr 23, 2004 at 14:21 UTC

    You were right the first time. There really is no difference. Why don't next and last work for you?

    I interpreted that to mean that under -p you cant use next to skip the print, otherwise I was confused too.


    ---
    demerphq

      First they ignore you, then they laugh at you, then they fight you, then you win.
      -- Gandhi


      :o very nice i found it very useful! Thanks! :D

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://324988]
help
Sections?
Information?
Find Nodes?
Leftovers?
    Notices?
    hippoepoptai's answer Re: how do I set a cookie and redirect was blessed by hippo!
    erzuuliAnonymous Monks are no longer allowed to use Super Search, due to an excessive use of this resource by robots.