Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl Monk, Perl Meditation
 
PerlMonks  

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

by smithfarm (Initiate)
on Oct 20, 2013 at 08:19 UTC ( [id://1059000]=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?

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.

Replies are listed 'Best First'.
Re: Answer: How can I add all the numbers in an array with out doing a foreach loop?
by MidLifeXis (Monsignor) on Oct 21, 2013 at 13:03 UTC

    While these will "work", they confuse the issue of what you are trying to accomplish.

    grep is used to select items from a list.

    map is used to transform one list into another.

    Both take one list and return another list. In my opinion, using grep or map for tasks outside of that scope is being 'too cute', and will cost time later when maintenance time comes around. It takes more work (albeit not much) to comprehend the intent of these code blocks. Make it easier on your future-self and avoid using map and grep for this purpose.

    --MidLifeXis

Re: Answer: How can I add all the numbers in an array with out doing a foreach loop?
by Eily (Monsignor) on Oct 22, 2013 at 07:44 UTC

    It does work, but you'll find that there is a very widespread rule among Perl users which is "Do not use grep or map in a void context". Often the argument is that it is because it uses extra memory for nothing. But Perl is smart enough and turning all uses of grep and map in a void context into a simple for loop could work fine. The problem, as MidLifeXis already said, is not that they don't do it right, is that it's not what they mean.

    A for loop on the contrary was made for this kind of things. And the postfix version is even shorter than a grep or map in this case $sum+=$_ for @array;

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others avoiding work at the Monastery: (3)
As of 2024-06-18 12:12 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found

    Notices?
    erzuuli‥ 🛈The London Perl and Raku Workshop takes place on 26th Oct 2024. If your company depends on Perl, please consider sponsoring and/or attending.