Beefy Boxes and Bandwidth Generously Provided by pair Networks
The stupid question is the question not asked
 
PerlMonks  

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

by KM (Priest)
on Jun 09, 2000 at 20:31 UTC ( [id://17360]=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?

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

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others rifling through the Monastery: (1)
As of 2024-04-24 23:58 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found