in reply to Having problems with addition in sub

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.

  1. At line 12 of your code, @fred contains the values ( 1, 3, 5, 7, 9 ).
  2. 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 )).
  3. 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.
  4. Second pass, $_ contains 3, so the value in $_ is 7, and $number thus becomes 10.
  5. 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.
  6. The same thing occurs for passes four and five, where $_ becomes 7 and 9, respectively.
  7. 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.

Replies are listed 'Best First'.
Re^2: Having problems with addition in sub
by GrandFather (Saint) on Oct 01, 2006 at 04:45 UTC

    A nit (which I'm sure atcroft knows about) for the benefit of OP: it is important to remember from time to time that $_ is actually an alias to each element in the list being processed by a for loop (or map or grep). This is important because if you change $_ inside the loop the current list element's value is altered. Consider:

    use strict; use warnings; my @array = qw(1 3 5 6); ++$_ for @array; print "@array";

    Prints:

    2 4 6 7

    Each of the elements in the array @array has been incremented by the for loop.


    DWIM is Perl's answer to Gödel