spikey_wan has asked for the wisdom of the Perl Monks concerning the following question:
Hello World!\n
Often when I'm creating Tk GUI based scripts, I include a Cancel button for the longer operations.
However, the only way I have found to make the cancel button work is to have many 'return if $cancel;' type commands interspersed all through the subroutine, which can get very tedious if the routine is quite long and complicated.
So, I was wondering, is there an easier way to get a subroutine to terminate?
Thanks,
Spike.
In the following simple example, as the loop is small, it's easy to include a 'return if $cancel;' command, but imagine that the start subroutine is a very long and complicated routine, without a simple loop structure. Then you've got to add 'return if $cancel;' over and over again.
use strict; use warnings; use Tk; use Tk::ROText; my $cancel = 0; my $mw = MainWindow -> new (-title => " loop test"); $mw -> withdraw; $mw -> minsize (qw(700 400)); my $status = $mw -> Scrolled ("ROText", -scrollbars => 'e', -background => 'white', ) ->pack( -expand => 1, -fill => 'both', ); $status -> configure(-wrap => 'word'); my $exit = $mw -> Button ( -text , 'Exit', -command, \&my_exit, ) -> pack (-side, 'left'); my $start = $mw -> Button ( -text , 'Start', -command, \&start, ) -> pack (-side, 'right'); $mw -> Popup; $mw -> focus; MainLoop(); sub start { $cancel = 0; $start -> configure ( -state => 'disabled', -relief => 'sunken'); $exit -> configure ( -text => 'Cancel', -command => \&cancel); for (1..100) { # last if $cancel; output ("$_\n"); sleep 2; } done(); } sub cancel { output ("Cancelling...\n"); $cancel =1; } sub my_exit { exit(); } sub done { $start -> configure ( -state => 'normal', -relief => 'raised'); $exit -> configure ( -text => "Exit", -command => \&my_exit); output ("Done.\n"); } sub output { my $text = $_[0]; $status->insert('end', "$text"); $status -> see ('end'); $mw->update; }
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: One shot way to end a sub?
by Fletch (Bishop) on Oct 25, 2004 at 10:59 UTC | |
|
Re: One shot way to end a sub?
by thospel (Hermit) on Oct 25, 2004 at 11:18 UTC | |
|
Re: One shot way to end a sub?
by Anonymous Monk on Oct 25, 2004 at 11:23 UTC |