Beefy Boxes and Bandwidth Generously Provided by pair Networks
good chemistry is complicated,
and a little bit messy -LW
 
PerlMonks  

How can I add all the numbers in an array with out doing a foreach loop?

( #17352=categorized question: print w/ replies, xml ) Need Help??
Contributed by draco_iii on Jun 09, 2000 at 20:14 UTC
Q&A  > arrays


Description:

That is, I want to avoid having to write any kind of explicit loop, such as:
my $sum = 0; for ( @numbers ) { $sum += $_; }
I'd rather do it in a single statement. Of course, I could wrap the above in a sub, but are there any better ways?

Answer: How can I add all the numbers in an array with out doing a foreach loop?
contributed by chromatic

Using eval, which of course has inherent dangers:

@e = (1,2,3,4); $sum = eval join '+', @e;
Answer: How can I add all the numbers in an array with out doing a foreach loop?
contributed by brother ab

In functional style, using reduce from List::Util:

@a = (1..10); use List::Util qw(reduce); $sum = reduce { $a + $b } @a;
Answer: How can I add all the numbers in an array with out doing a foreach loop?
contributed by myuserid7

List::Util provides a sum() function:

use List::Util qw(sum); $sum = sum(1..10);
Answer: How can I add all the numbers in an array with out doing a foreach loop?
contributed by I0

For a positive sum:

unpack "%123d*" , pack( "d*", @numbers);

For a signed long:

unpack "l", pack( "l", unpack( "%32d*", pack( "d*", @numbers)));
Answer: How can I add all the numbers in an array with out doing a foreach loop?
contributed by DStaal

Just to have the one-line loop on here, since your real complaint is to get it all on one line:

(Note that you'd have to declare $sum someplace before the loop yet.)

@a = (1..10); $sum += $_ for @a;
Answer: How can I add all the numbers in an array with out doing a foreach loop?
contributed by aaron_baugher

Surprised no one's added the Lisp-style recursive solution yet:

sub radd { return( defined $_[0] ? $_[0] + radd(@_[1..$#_]) : 0 ); } my $sum = radd(1..10);
Answer: How can I add all the numbers in an array with out doing a foreach loop?
contributed by lkench

Someone might be interested in:

my $sum = [map {$sum +=$_} @arrayToSum]->[$#arrayToSum];
I found it useful anyway.

--lkench

Answer: How can I add all the numbers in an array with out doing a foreach loop?
contributed by smithfarm

Use the grep function:

my $sum; grep { $sum += $_ } @arrayToSum;
Or, equivalently, use the map function:
my $sum; map { $sum += $_ } @arrayToSum;
Both grep and map apply the code in the code block to each element of @arrayToSum. The _result_ of the grep/map function is not interesting to us in this case, so we ignore it.

Please (register and) log in if you wish to add an answer



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.
  • Log In?
    Username:
    Password:

    What's my password?
    Create A New User
    Chatterbox?
    and the web crawler heard nothing...

    How do I use this? | Other CB clients
    Other Users?
    Others lurking in the Monastery: (4)
    As of 2015-07-06 04:22 GMT
    Sections?
    Information?
    Find Nodes?
    Leftovers?
      Voting Booth?

      The top three priorities of my open tasks are (in descending order of likelihood to be worked on) ...









      Results (70 votes), past polls