On Mon, May 24, 2010 at 12:49 PM, Weizhong Dai <weizhong....@gmail.com>wrote:
> Hi guys, I met a problem. > When I tried this script below: > > //-------------------------------------------------------------------- > sub print_instruction { > my ($disk, $start, $end) = @_; > print "Move disk #$disk from $start to $end.\n"; > } > > sub hanoi { > my ($n, $start, $end, $extra, $m) = @_; > if ($n == 1) { > $m->(1, $start, $end); > } else { > hanoi($n-1, $start, $extra, $end); > $m->($n, $start, $end); > hanoi($n-1, $extra, $end, $start); > } > } > > &hanoi(3, 'A', 'C', 'B', \&print_instruction); > //------------------------------------------------------------------------- > > I got a error : Undefined subroutine &main:: called at .... > this is an example in <High Order Perl>, so it should not be wrong, I > just don't known what is the problem. > Plz help me. > > -- > To unsubscribe, e-mail: beginners-unsubscr...@perl.org > For additional commands, e-mail: beginners-h...@perl.org > http://learn.perl.org/ > > > No idea why Perl would cry about &main, my knowledge of Perl internals is not that good yet. But I would bet that the problem lies in the following: sub hanoi expects to receive 5 parameters, in side the sub you are calling is once again but now with only 4 parameters. hanoi($n-1, $start, $extra, $end); $m->($n, $start, $end); hanoi($n-1, $extra, $end, $start); My guess is that Perl when you are pulling in the parameters using the my ( ... ) = @_; line at the beginning of the sub places a ref to main at the end for your convenience, thus the call to $m-> will be interpreted as a call to &main which in turn upsets Perl. I would try to hand in $m in the two recursive calls inside the hanoi sub. hanoi($n-1, $start, $extra, $end, $m); $m->($n, $start, $end); hanoi($n-1, $extra, $end, $start, $m); That should do the trick... Don't trust the written word, in the end it was a human doing the writing so mistakes are inevitable. ;-) Regards, Rob