$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
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |