in reply to adding a column of integers

perl -lne "$sum+=$_}{print $sum"

Replies are listed 'Best First'.
Re^2: adding a column of integers
by Eimi Metamorphoumai (Deacon) on Sep 02, 2004 at 14:19 UTC
    Or more verbose, but more understandable (without delving into the actual expansion of -n)
    perl -lne '$sum+=$_; END{print $sum}'
    The END block is executed after everything else. You can also use a corresponding BEGIN block before anything else runs, and there are others (CHECK and INIT, having to do with compile time) for fancy stuff.
Re^2: adding a column of integers
by Smylers (Pilgrim) on Sep 02, 2004 at 16:10 UTC

    If you're in the mood for doing sneaky tricks with -n then why not be really sneaky:

    perl -lne '$;+=$_}{print$'

    Smylers

        That's overkill; miss out 3 of the characters and it still works:

        perl -lpe '$-+=$_}{$_=$-'

        Smylers

Re^2: adding a column of integers
by Random_Walk (Prior) on Sep 02, 2004 at 15:51 UTC

    update - whoops

    I just saw his tail -1 at the end, he is looking for a final total not a running one, DOH!. So option 2 below works just fine

    Original dumb post

    This does not work for me, is this my old perl (5.005_03) or am I doing something wrong ? If I add a continue it will work. Here is some output, I have added the > before the numbers I entered just for clarity.
    :perl -lne "$sum+=$_}{print $sum" syntax error at -e line 1, near "+=" Execution of -e aborted due to compilation errors. :perl -lne '$sum+=$_}{print $sum' >1 >2 >3 :perl -lne '$sum+=$_}continue{print $sum' >1 1 >2 3 >3 6 >4 10
    Cheers,
    R.