Given this Perl/Tkx code fragment:
@itemList = ({'attrib1' => 'name1', 'attrib2' => 'value1'},
{'attrib1' => 'name2', 'attrib2' => 'value2'});
$row = 0;
foreach $item (@itemList) {
push(@btn_list, new_ttk__button(-text => $item->{'attrib1'}, -command => sub {do_something($item->{'attrib2'});}));
$btn_list[-1]->g_grid(-column => 0, -row => $row);
$row++;
}
(In the real program @itemList is populated from a user editable config file.)
I do see two buttons labeled 'name1' and 'name2'. But when I click on either button it seems that the parameter that is passed to the callback is always $itemList[1]->{'attrib2'}; i.e. 'attrib2' of the last element of the @itemList array. What I would like is to have the first button call do_something($itemList[0]->{'attrib2'} and the second call do_something($itemList[1]->{'attrib2'}.
What am I doing wrong, please and thank you?
You have encountered a subtle feature of
forloops in Perl. First the solution: usemyin the for loop. Then$itemwill be able to create a proper closure in the anonymous sub you declare later in the loop.Further explanation: Perl implicitly localizes the subject variable of a for loop. If you don't use
myin the for loop, the loop will be using a localized version of a package variable. That makes your code equivalent to:Your anonymous subs still refer to the
$main::itempackage variable, whatever value that variable holds at the time that those subroutines are invoked, which is probablyundef.Shorter solution:
use strictAdditional proof-of-concept. Try to guess what the following program outputs:
Here's the answer: