The answer given is essentially correct. However, it is
important to note that the problem is unrelated to
$fn being or not being is lexical variable. The
problem is simply that the
sub being created
(
sub {&Load ($fn)}; why the ampersand?) says
"pass
Load the value of
$fn".
But that's the value when the sub is executed, not when it
was defined!
The fix is to change that by making each iteration of the loop
refer to a different lexical variable!
But it still creates many subroutines and closures.
Perl/Tk provides another syntax for callbacks that is
better in this case; see
Tk::callbacks
for the details.
Meanwhile, here's some sample code:
#!/usr/local/bin/perl -w
use strict;
use Tk;
my $mw = new Tk::MainWindow;
my $mb = $mw->Menubutton(-text => 'Test')->pack(-side => 'left');
sub Select {
my $val = shift;
my $top = $mw->Toplevel(-title => "Selection $val");
$top->Button(-text => "Close Select($val)",
-command => ['destroy', $top])->pack;
}
for(1..10) {
$mb->command(-label => $_,
-command => [\&Select, $_]);
}
MainLoop;
Build your callbacks by giving a list reference of the
sub and the arguments you'd like passed. So it's
the same sub each time, and only a list of the arguments
is stored.
Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
Read Where should I post X? if you're not absolutely sure you're posting in the right place.
Please read these before you post! —
Posts may use any of the Perl Monks Approved HTML tags:
- a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
| |
For: |
|
Use: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.