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

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • 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:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.