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.


In reply to Re: Having problems with addition in sub by atcroft
in thread Having problems with addition in sub by bluethundr

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.