in reply to Perl/Tk Menus

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.