in reply to Use of uninitialized value in print at line 20 (#1)

Hi,

as already mentioned by other monks, your direct problem is an off-by one error.

I would like however to point to other serious problems in your code, although they happen to have no direct consequences in this specific case. <p Since your aim is apparently to "print each number in integer array in new line without using for or while loop", using recursion is a very natural solution. However, in general, recursive functions should in general depend only on arguments passed to them and should not rely on global variables. Especially your use of the $counter global variable is a recipe for disaster when things get a bit more complicated. Also, the way you're using $inputArrayLen is a mistake, since you're passing as a parameter to your recursive subroutine, but, since you're not using the parameters passed to the sub, you are actually using a global copy of that value.

You could fix it this way:

use strict; use warnings; my @inputArray = (1..8); my $counter = 0; traverseArray($counter); sub traverseArray { my $counter = shift; return if $counter >= @inputArray; print "$inputArray[$counter]\n"; traverseArray($counter+1); }
This solution still has one global variable, i.e. the @inputArray array. To me, this is not a major problem and you could live with that, but, ideally, it would be better to get rid of it and also pass the array as an argument. It could be something like this:
# same initialization as before traverseArray($counter, @inputArray); sub traverseArray { my ($counter, @input) = @_; return if $counter >= @input; print "$input[$counter]\n"; traverseArray($counter+1, @input); }
That's cleaner and that's OK in theory, but that is not very efficient because that makes a local copy of the array each time the subroutine is called, and that can be an overhead (in terms of momory size and speed performance), especially if the array is large.

There are various ways to avoid that, but they are using some slightly advanced concepts (e.g. references or closures) which you probably would want to learn a bit later. Both solutions above are already a good starting point.