note
Anonymous Monk
<p> If you had <c> use strict; use warnings: </c> you would have been warned
<c>
Variable "$text" will not stay shared at file line 1
</c>
<p> If you had used [mod://diagnostics] you'd have gotten <c>(W closure) An inner (nested) named subroutine is referencing a
lexical variable defined in an outer named subroutine.
When the inner subroutine is called, it will see the value of
the outer subroutine's variable as it was before and during the *first*
call to the outer subroutine; in this case, after the first call to the
outer subroutine is complete, the inner and outer subroutines will no
longer share a common value for the variable. In other words, the
variable will no longer be shared.
This problem can usually be solved by making the inner subroutine
anonymous, using the sub {} syntax. When inner anonymous subs that
reference variables in outer subroutines are created, they
are automatically rebound to the current values of such variables.
</c>
<p> Read [Tutorials]: [id://268891|Closure on Closures], [id://213855|Lexical scoping like a fox]
<p> If you're going to use named subs, use pre-declare any [doc://my] variables (like $tl and $text ) in the largest possible scope (before any sub definitions) or simply use [doc://our] globals, and you'll be fine with strict/warnings, and you'll avoid calling methods on destroyed object ( you'll avoid <i> Failed to AUTOLOAD... </i> )
<p> Or , keep what you have, but use anonymous sub/anonymous closure
<c>
sub do_top {
if ( !Exists($tl) ) {
$tl = $mw->Toplevel;
$tl->title('Help');
$tl->geometry("1000x700");
my $frame = $tl->Frame()->pack;
my $lab = $tl->Label()->pack;
my $ent = $tl->Entry()->pack;
#### ANONYMOUS SUB , ANONYMOUS CLOSURE,
#### CLOSED OVER LEXICAL $text
#### $text is lexical to if {} block in do_top
my $text = $tl->Scrolled('Text');
my $push_button2 = sub {
$text->insert( 'end', "You pushed button2\n" );
};
$tl->Button( -text => 'Exit', -command => sub { $tl->destroy; } )->pack;
$tl->Button( -text => 'Open File1', -command => $push_button2 )->pack;
$text->pack();
} else {
$tl->deiconify;
$tl->raise;
}
}
</c>
1001015
1001015
11