grep is right-the problem is in the foreach in your total function. By saying @_[$_] inside your loop, you are using values from the array passed in (@fred) to pick the items to add.
- At line 12 of your code, @fred contains the values ( 1, 3, 5, 7, 9 ).
- At line 13, you call your total function. At line 5 (just inside the total function), @_ contains the content of @fred from the main body (i.e., ( 1, 3, 5, 7, 9 )).
- Now, when you begin the foreach loop, you are looping thru the values (1, 3, 5, 7, 9), but inside the loop $_ is taking on the value you are currently working with, so on the first pass, $_ contains the value 1, so the value at index 1 of @_ (i.e., 3), is added to $number, giving it the value 3.
- Second pass, $_ contains 3, so the value in $_ is 7, and $number thus becomes 10.
- On pass three, $_ contains 5, which is undefined in @_ (a warning would be generated were you using either '-w' or 'use warnings;'), so $number does not change.
- The same thing occurs for passes four and five, where $_ becomes 7 and 9, respectively.
- Thus, $number contains 10 when returned from the first call to &total.
A similar situation will occur if the user provides numbers that exceed the number of values they provide.
HTH.