$inputArrayLen is set equal to 8. There are 8 elements in the array. You start counting from 0. You keep going until $counter is greater than $inputArrayLen.

So you print elements 0, 1, 2, 3, 4, 5, 6, 7... all of which are fine. Element 0 contains the value 1. Element 7 contains the value 8. What does element 8 contain? An undefined value. Element 8 is the 9th element in the array.

Change <= to < and it's fixed. This is an off by one error -- a common result of forgetting about zero-based numbering.

You have some other problems, but they're not actually causing trouble. One is how you pass parameters. You never actually use the parameter passed into the subroutine. Instead, you just absorb the same variable because it happens to be within the same lexical scope. Have a look at perlsyn for a better understanding of scoping and parameter passing. Minimally, it should follow this pattern:

foo($value); sub foo { my ($v) = @_; print "$v\n"; }

Also, it seems like your goal is a recursive solution. Usually in exercises where recursion is a goal, it's preferable to store state within the subroutine's parameters. Here's an example.

my @inputArray = (1,2,3,4,5,6,7,8); traverseArray2(\@inputArray); sub traverseArray2 { my ($aref, $counter) = (shift, shift // 0); return if $counter >= @$aref; print $aref->[$counter], "\n"; traverseArray2($aref, $counter+1); }

You can even get rid of the counter and eliminate the call-stack overhead like this:

my @inputArray = (1,2,3,4,5,6,7,8); traverseArray3(@inputArray); sub traverseArray3 { return unless @_; print shift, "\n"; goto &traverseArray3; }

Dave


In reply to Re: Use of uninitialized value in print at line 20 (#1) by davido
in thread Use of uninitialized value in print at line 20 (#1) by dishantarora

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.