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

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

by myuserid7 (Scribe)
on Aug 15, 2006 at 10:03 UTC ( [id://567413]=note: print w/replies, xml ) Need Help??


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

List::Util provides a sum() function:
use List::Util qw(sum); $sum = sum(1..10);
  • Comment on Re: How can I add all the numbers in an array with out doing a foreach loop?
  • Download Code

Replies are listed 'Best First'.
Re: Answer: How can I add all the numbers in an array with out doing a foreach loop?
by borisz (Canon) on Aug 16, 2006 at 09:48 UTC
    Just for fun, does the question make any sense?
    use List::Util qw/reduce/; my $sum = reduce { $a + $b } 1..10;
    Boris
Re: Answer: How can I add all the numbers in an array with out doing a foreach loop?
by b10m (Vicar) on Aug 15, 2006 at 10:49 UTC

    ... and List::Util::sum() doesn't use a foreach loop?

    --
    b10m

    All code is usually tested, but rarely trusted.

      Er, no it is XS code, it does interate over the list it gets as an argument using for(index = 1 ; index < items ; index++) but I don't think that counts as a foreach

      /J\

      A reply falls below the community's threshold of quality. You may see it by logging in.
Re: Answer: How can I add all the numbers in an array with out doing a foreach loop?
by furry_marmot (Pilgrim) on Aug 16, 2006 at 13:29 UTC
    I just have to ask how the heck hard is it to write this:

    $sum += $_ for @array

    And notice there's no foreach loop, which the Camel clearly states is a synonym for for anyway (see "perldoc perlsyn", 'Foreach Loops'), so maybe I'm not clear on what you're asking.

    --marmot

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://567413]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others taking refuge in the Monastery: (5)
As of 2024-04-19 15:26 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found