Hello,
I am trying some code from Higher Order Perl by Mark Jason Dominus and it doesn't work. When I tried to replace the original print statements with a reference to a subroutine (print_instruct ion) that prints, I kept getting the error message "Undefined subroutine &main:: called at hanoi.pl line 27." Line 27 is marked in the code below in a comment (it shows as line 21 in the posting below). It doesn't like the dereferencing of the subroutine reference I passed in. This was cut and pasted from his website. The only things I added were the print_instructi on subroutine and its calls, going strictly by what's in the book.
I am using Perl 5.8.8, ActiveState build 820, built Jan. 23, 2007 on Windows XP.
I am trying some code from Higher Order Perl by Mark Jason Dominus and it doesn't work. When I tried to replace the original print statements with a reference to a subroutine (print_instruct ion) that prints, I kept getting the error message "Undefined subroutine &main:: called at hanoi.pl line 27." Line 27 is marked in the code below in a comment (it shows as line 21 in the posting below). It doesn't like the dereferencing of the subroutine reference I passed in. This was cut and pasted from his website. The only things I added were the print_instructi on subroutine and its calls, going strictly by what's in the book.
I am using Perl 5.8.8, ActiveState build 820, built Jan. 23, 2007 on Windows XP.
Code:
# hanoi(N, start, end, extra)
# Solve Tower of Hanoi problem for a tower of N disks,
# of which the largest is disk #N. Move the entire tower from
# peg 'start' to peg 'end', using peg 'extra' as a work space
sub print_instruction
{
my ($disk, $start, $end) = @_;
print "Move disk #$disk from $start to $end.\n";
}
hanoi(3, 'A', 'C', 'B', \&print_instruction);
sub hanoi
{
my ($n, $start, $end, $extra, $move_disk) = @_;
if ($n == 1)
{
$move_disk->(1, $start, $end); # line 27
}
else
{
hanoi($n-1, $start, $extra, $end); # Step 2
$move_disk->($n, $start, $end);
hanoi($n-1, $extra, $end, $start); # Step 4
}
}
sub print_instruction
{
my ($disk, $start, $end) = @_;
print "Move disk #$disk from $start to $end.\n";
}
Comment