holli has asked for the wisdom of the Perl Monks concerning the following question:

Monks,

I have just bought Mastering Perl/Tk and play with some examples. While doing that I stumbled over the "after" method and wrote the following code:
use Tk; my $mw = MainWindow->new(); my $level = 0; my $id = $mw->after (1, \&amp;_after); sub _after { if ( $level < 5 ) { $level++; my $id = $mw->after (1, \&amp;_after); } else { $level--; } print "$level"; } MainLoop; 1;
The ouput of this in my system (Win32, Perl 5.8) is "123454" and not "123454321" as I expect. Also the program seems to be still busy, because there is an hourglass cursor.

I'm seeking for enlightment why the program doesn't behave as I expect it to.


holli, /regexed monk/

Replies are listed 'Best First'.
Re: Perl/Tk: recursive "after" method issue
by Errto (Vicar) on Feb 02, 2006 at 21:38 UTC
    The reason this is happenening is that after isn't recursive. What calling after does is tell the Tk MainLoop, once it next receives control, to run the specified subroutine after the specified amount of time. That is to say, when your _after sub is called the second time, the first iteration has already completed, having printed the value "1", and so on.
Re: Perl/Tk: recursive "after" method issue
by zentara (Cardinal) on Feb 02, 2006 at 21:41 UTC
    The after method only executes once. So you count up to 5, each time reiniting the timer. The 6th time, you decrease level, but don't reinit the timer. So after it prints the last 4, there is no timer going. Use repeat to keep it repeating.

    Just for your information, the way Gtk2 does timers, is the timer will keep going if it's callback returns TRUE, or the timer will stop if the timer's callback returns FALSE.


    I'm not really a human, but I play one on earth. flash japh