in reply to
Recursion Confusion

Sometimes I find with recursion it helps to add some tracking to help visualise what path is being followed.

Hope this helps

`use warnings;
use strict;
my $ndisks = 3;
hanoi( $ndisks, 'A', 'C', 'B', 0 );
sub hanoi
{
my( $n, $start, $end, $extra, $depth ) = @_;
print "\t"x$depth . "n=$n, start=$start end=$end extra=$extra\
+n";
if( $n == 1 )
{
print "\t"x$depth . "Move disk #$n from $start to $end
+\n";
}
else
{
$depth++;
print "\t"x$depth . "Calling hanoi 1\n";
hanoi( $n-1, $start, $extra, $end, $depth);
print "\t"x$depth . "Move disk #$n from $start to $end
+\n";
print "\t"x$depth . "Calling hanoi 2\n";
hanoi ($n-1, $extra, $end, $start, $depth);
}
}
`

`n=3, start=A end=C extra=B
Calling hanoi 1
n=2, start=A end=B extra=C
Calling hanoi 1
n=1, start=A end=C extra=B
Move disk #1 from A to C
Move disk #2 from A to B
Calling hanoi 2
n=1, start=C end=B extra=A
Move disk #1 from C to B
Move disk #3 from A to C
Calling hanoi 2
n=2, start=B end=C extra=A
Calling hanoi 1
n=1, start=B end=A extra=C
Move disk #1 from B to A
Move disk #2 from B to C
Calling hanoi 2
n=1, start=A end=C extra=B
Move disk #1 from A to C
`