[ back to toc ]

Adding all elements in an array

Date: 2002/02/27 10:40

Q:
Hello Peter:

I'm glad you can answer questions regarding perl, because I got to a
little obsticle I haven't been able solve.

Im working on a simple Take Out Menu order form.

All Item prices checked by the user, are parsed to the script under the
variable "prices" and are getting accummulated in an array.

@prices = (345,579,875,346);

Now is time to add up all of the items in this array together so I can
have a total.

I wish I could do this :

$Total = $prices[0] + $prices[1] + $prices[2] + $prices[3];

I can't do this because I never know how many prices will be accummulated
in the array since this depends on how many items are checked out in the
previous form.

Im sure there must be an easy way to do this but I checked on all my books
and can't find the answer.

Thank you in adavance...
*NAME-DELETED*
sebglanzer@yahoo.com

A:
$Total = 0;
for $i (0 .. $#prices){$Total += $prices[$i];}

Regards,
Peter

[ back to toc ]