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


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

The loopish way would be like:

@e = (1,2,3,4); my $foo; $foo += $_ for @e;

or you can do something like (still a loop, but you need to loop in some way for this):

@e = (1,2,3,4); print eval join '+', @e;

Cheers,
KM

Replies are listed 'Best First'.
Re: Answer: How can I add all the numbers in an array with out doing a foreach loop?
by ack (Deacon) on Sep 10, 2009 at 17:16 UTC

    You can do it with grep as:

    #!/user/bin/perl use strict; use warnings; my @array = (1,2,3,4,5,6,7,8,9,10); my $sum = 0; grep{$sum += $_} @array; print "\$sum = $sum\n"; exit(0);

    The result is:

    $sum = 55
    ack Albuquerque, NM
RE: Answer: How can I add all the numbers in an array with out doing a foreach loop?
by Adam (Vicar) on Jun 09, 2000 at 23:43 UTC
    Your first answer is really a foreach loop. Remember that for and foreach are synonyms. Your second answer, however, is very slick! Nice.
      Hence me saying 'The loopish way..'. Actually, they are both loops. I believe internally join() still loops to actually join all the elements. It isn't a loop like a for or foreach.

      Cheers,
      KM

        Right, I was just pointing out that using 'for' doesn't answer the question of not using a 'foreach' loop. It looks kind of funny when the question stipulates that the person doesn't want to use something, and then you use it in your answer. Thats all.
Re: Answer: How can I add all the numbers in an array with out doing a foreach loop?
by Tux (Canon) on Sep 10, 2009 at 19:07 UTC
    $ perl -wle'my@x=(0..10);$"="+";$\=~s/$/"@x"/ee;print""' 55 $

    Enjoy, Have FUN! H.Merijn