Re: adding a column of integers
by borisz (Canon) on Sep 02, 2004 at 13:23 UTC
|
Whats wrong with your solution?
Here is my one:
perl -ple '$_=$s+=$_'
| [reply] [d/l] |
Re: adding a column of integers
by ccn (Vicar) on Sep 02, 2004 at 13:28 UTC
|
| [reply] [d/l] |
|
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. | [reply] [d/l] [select] |
|
| [reply] [d/l] [select] |
|
perl -lpe '$-+=$_}{$_+=$-}{'
| [reply] [d/l] |
|
|
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. | [reply] [d/l] |
Re: adding a column of integers
by sleepingsquirrel (Chaplain) on Sep 02, 2004 at 14:52 UTC
|
Choose from solutions in 47 different languages.
-- All code is 100% tested and functional unless otherwise noted.
| [reply] |
Re: adding a column of integers
by kscaldef (Pilgrim) on Sep 02, 2004 at 16:14 UTC
|
perl -MList::Util=sum -le 'print sum <>' | [reply] [d/l] |
Re: adding a column of integers
by sintadil (Pilgrim) on Sep 02, 2004 at 18:14 UTC
|
perl -le 'map{$total += $_} <>; print $total' | [reply] [d/l] |
|
| [reply] |
|
| [reply] [d/l] |
|
I would use a grep instead of a map... :-)
| [reply] |
Re: --- adding a column of integers
by Anonymous Monk on Sep 02, 2004 at 14:34 UTC
|
awk '{s += $0} END {print s}'
perl -le '$"="+"; print eval "@{[<>]}"'
| [reply] [d/l] |
|
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
| [reply] [d/l] [select] |
Re: adding a column of integers
by ambrus (Abbot) on Jun 26, 2006 at 18:25 UTC
|
ruby -we 'puts $<.inject(0) {|a, x| a + x.to_i };'
| [reply] [d/l] |
|
| [reply] [d/l] [select] |