lbrandewie has asked for the wisdom of the Perl Monks concerning the following question:
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
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Closure confusion in Tkx (declarations in loops)
by LanX (Saint) on Jul 13, 2019 at 12:50 UTC | |
by LanX (Saint) on Jul 13, 2019 at 13:53 UTC | |
by lbrandewie (Acolyte) on Jul 13, 2019 at 20:28 UTC | |
by AnomalousMonk (Archbishop) on Jul 13, 2019 at 22:01 UTC | |
by LanX (Saint) on Jul 13, 2019 at 21:35 UTC | |
|
Re: Closure confusion in Tkx
by AnomalousMonk (Archbishop) on Jul 13, 2019 at 13:37 UTC | |
|
Re: Closure confusion in Tkx
by BillKSmith (Monsignor) on Jul 13, 2019 at 13:58 UTC | |
by LanX (Saint) on Jul 13, 2019 at 16:16 UTC |