[ back to toc ]

Adding all elements in an array

Date: 2002/03/06 12:05

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...

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


Hello Peter:

Thanx a million for your prompt response, and for the lifesaver line..!!!

It worked wonders when I used it in a simple take out menu script which
reads the input straight from the form... but now I tried using the same
line in a little Part Ordering script (shopping cart Stile), and for some
reason even if I spent hours on it, I cant extract the price values shown
on the browser, to include them in a @Price array.

Only on a last resort situation i try bothering others ... so I hope you
can have a look at it.

I have uploaded the one page script with the example so you can picture
what Im talking about. I hope its not too much to ask that you try the
form and tell me what I may be missing.

The form is at:

Series: M-100-range
Model: 600 or 700

The code is at:

What I need to do with this script is not only add but subtract the
appropiate values, (but if I can just get you to show me how I can find
the values to put them in an array, I more than likely be able to do the
math on my own).

Much appreciated.. and thanx again for the first answer.

All the best
I have had a look at it, but unfortunately this is too much work for this
service to track the issue.


[ back to toc ]