Hey Perl Monks,
I, a poor hacker, am confounded by the following problem. This isn't the problem I'm having (exactly), it's just the simplest case I can reduce it to.
Let's say you wanted to build a simple text file editor, using the following code:
use Tkx; use strict; our (@data, @editctls, @buttons); open IN, "test.txt"; flock IN, 1; @data = <IN>; close IN; chomp @data; our $mw = Tkx::widget->new("."); for (my $x = 0; $x < @data; $x++) { push @editctls, $mw->new_ttk__entry(-width => 30, -textvariable => + \$data[$x]); $editctls[$x]->g_grid(-row => $x, -column => 0); push @buttons, $mw->new_ttk__button(-text => "Update", -command => + sub { update($x); } ); $buttons[$x]->g_grid(-row => $x, -column => 1); } Tkx::MainLoop(); sub update { my $which = shift; open DATA, "+<test.txt"; my @stuff = <DATA>; $stuff[$which] = $data[$which] . "\n"; seek DATA, 0, 0; print DATA @stuff; truncate DATA, tell(DATA); close DATA; }
And I'm using the following text file for testing:
this is a text file
The problem is with the update buttons. When clicked, they send the current value of $x to the update subroutine, not the value of $x when the anonymous sub was created. I had thought that when anonymous subs refer to lexical variables, they created a closure, but apparently not so in this case. Am I missing something? Is there a correct way to do this?
I did try moving the control creation logic to an actual sub but it made no difference.
Thanks,
Lars Brandewie
In reply to Closure confusion in Tkx by lbrandewie
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |