Beefy Boxes and Bandwidth Generously Provided by pair Networks
P is for Practical
 
PerlMonks  

adding a column of integers

by Anonymous Monk
on Sep 02, 2004 at 09:11 UTC ( #387897=perlquestion: print w/replies, xml ) Need Help??

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

Hi Folks, Whats a nice one liner for adding a column of figures using perl ?
I'm not particularly happy with my solution

 perl -ple '$sum=$_+$sum;$_=$sum;'|tail -1

but it works and reflects my baby-perl nicely.
I need some enlightenment to reach my next perl karma.

Replies are listed 'Best First'.
Re: adding a column of integers
by borisz (Canon) on Sep 02, 2004 at 09:23 UTC
    Whats wrong with your solution?
    Here is my one:
    perl -ple '$_=$s+=$_'
    Boris
Re: adding a column of integers
by ccn (Vicar) on Sep 02, 2004 at 09:28 UTC

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

      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.

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

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

      Smylers

      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.
Re: adding a column of integers
by sleepingsquirrel (Hermit) on Sep 02, 2004 at 10:52 UTC
    Choose from solutions in 47 different languages.


    -- All code is 100% tested and functional unless otherwise noted.
Re: adding a column of integers
by kscaldef (Pilgrim) on Sep 02, 2004 at 12:14 UTC
    perl -MList::Util=sum -le 'print sum <>'
Re: adding a column of integers
by sintadil (Pilgrim) on Sep 02, 2004 at 14:14 UTC
    perl -le 'map{$total += $_} <>; print $total'

      Note that this uses map in void context, which is bad except in newer Perls. It's not so horrible for a one-liner, though.

        My, my, my. Another fool who thinks he can appear to be smart by chiming the familiar song about map in void context. And to be really smart he mentions it's not so bad in modern perl.

        Forget about the map. The damage is done before the map is called. Executing <> in list context is slurping in the entire file. You've lost your constant memory solution right there. Regardless of the version of Perl you are using.

        I would use a grep instead of a map... :-)
Re: --- adding a column of integers
by Anonymous Monk on Sep 02, 2004 at 10:34 UTC
    awk '{s += $0} END {print s}' perl -le '$"="+"; print eval "@{[<>]}"'
      awk '{s += $0} END {print s}'

      Also

      (echo 0;sed s,$,+, inputfile;echo p)|dc
      or even (with gnu sed)
      sed ' G s/^ *\([0-9]*\) *\n\([0-9]*\)$/0\1pm0\2nb0/;td;d; :d;s/n\(\(b\).*0\|\)[^0]*$/nb98765432109876543210a0123456789\2/; s/\(.\)\(p.*\)\(.\)\(n.*\1\).*a.*\3/\2\4\3/; s/^0*\(.*\)p\(.*m\)0*\(.*\)\(.\).\{11\}$/0\1p\4\20\3/; /m0*n.*0/!bd; s/^\(.*\)p\(.*\)m.*/\1\2/;s/^0*//; h;$!d ' inputfile
      but the point of the OP was to improve his Perl skills.

      Update 2007 dec 6: see also Re: Golf: Adding up array elements

Re: adding a column of integers
by ambrus (Abbot) on Jun 26, 2006 at 14:25 UTC

    This ruby solution also deserves a mention as it doesn't slurp the file thanks to ruby iterators.

    ruby -we 'puts $<.inject(0) {|a, x| a + x.to_i };'

      perl -lne '$sum+=$_; END{print $sum}'
      and
      perl -le '$sum+=$_ while <>; print $sum'
      don't slurp either. <> is an iterator (in scalar context).

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://387897]
Approved by muntfish
Front-paged by ccn
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others musing on the Monastery: (4)
As of 2021-04-17 20:32 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found

    Notices?