http://www.perlmonks.org?node_id=1059000


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;