1 #!/usr/bin/perl -w 2 use strict; 3 4 my $recursion = 0; 5 my $count; 6 7 sub hanoi { 8 warn "invoked @_"; 9 my ($n, $start, $end, $extra) = @_; 10 $recursion++; 11 my $indent = " " x $recursion; 12 13 print$indent, "Entering hanoi($n, $start, $end, $extra)\n"; 14 15 if ($n == 1) { 16 warn $indent, "----------Move disk #1 from $start to $end.------------\n"; 17 $count++; 18 } else { 19 print"enter first hanoi\n"; 20 print"\$n is $n\n"; 21 hanoi($n-1, $start, $extra, $end); 22 print"AFTER first hanoi\n"; 23 print "\$n is $n\n"; 24 warn $indent, "----------$count Move disk #$n from $start to $end.\n"; 25 print " enter second hanoi\n"; 26 hanoi($n-1, $extra, $end, $start); 27 print " AFTER second hanoi\n"; 28 print " \$n is $n\n"; 29 } 30 print $indent, " __LEAVING hanoi($n, $start, $end, $extra)\n"; 31 print " \$n is $n\n"; 32 $recursion--; 33 } 34 35 hanoi(3, 'A', 'C', 'B'); invoked 3 A C B at ././perl.hanoi_f line 8. Entering hanoi(3, A, C, B) enter first hanoi $n is 3 invoked 2 A B C at ././perl.hanoi_f line 8. Entering hanoi(2, A, B, C) enter first hanoi $n is 2 invoked 1 A C B at ././perl.hanoi_f line 8. Entering hanoi(1, A, C, B) ----------Move disk #1 from A to C.------------ __LEAVING hanoi(1, A, C, B) $n is 1 AFTER first hanoi $n is 2 ----------1 Move disk #2 from A to B. enter second hanoi invoked 1 C B A at ././perl.hanoi_f line 8. Entering hanoi(1, C, B, A) ----------Move disk #1 from C to B.------------ __LEAVING hanoi(1, C, B, A) $n is 1 AFTER second hanoi $n is 2 __LEAVING hanoi(2, A, B, C) $n is 2 AFTER first hanoi $n is 3 ----------2 Move disk #3 from A to C. enter second hanoi invoked 2 B C A at ././perl.hanoi_f line 8. Entering hanoi(2, B, C, A) enter first hanoi $n is 2 invoked 1 B A C at ././perl.hanoi_f line 8. Entering hanoi(1, B, A, C) ----------Move disk #1 from B to A.------------ __LEAVING hanoi(1, B, A, C) $n is 1 AFTER first hanoi $n is 2 ----------3 Move disk #2 from B to C. enter second hanoi invoked 1 A C B at ././perl.hanoi_f line 8. Entering hanoi(1, A, C, B) ----------Move disk #1 from A to C.------------ __LEAVING hanoi(1, A, C, B) $n is 1 AFTER second hanoi $n is 2 __LEAVING hanoi(2, B, C, A) $n is 2 AFTER second hanoi $n is 3 __LEAVING hanoi(3, A, C, B) $n is 3