Beefy Boxes and Bandwidth Generously Provided by pair Networks
more useful options
 
PerlMonks  

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

by rajib (Novice)
on Aug 20, 2002 at 17:41 UTC ( [id://191530]=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?

Another recursive method:

@array = (1,2,3); print "SUM: ", sum($#array); sub sum { if ($_[0] == 0) { return $array[0]; } return $array[$_[0]] + sum($_[0]-1); } #note it's not efficient

This method's shortcoming is that the sub acts only on the global array "@array", and thus can't be easily applied to more than one array. A more elegant and useable recursive method was demonstrated earlier in this thread.

Originally posted as a Categorized Answer.

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others surveying the Monastery: (2)
As of 2024-04-25 20:19 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found