In your second example, the inconsistency between the button text and the sub is because of a difference in when the code is executed. When you call $mw->Button, the code you have in your constructor call is run right then, so "Button $_" is converted to a static string, and Button saves a copy of that static string somewhere, so even if $_ changes the button's text stays the same. But the anonymous sub you give as the argument to -command isn't executed until the button is clicked. By then the value of $_ will probably have changed, and so the sub will use the current value of $_ instead of its value when the constructor was called.

As others have said, your first example uses a closure, which implicitly creates a copy of the variable when the anonymous sub is created, so the sub refers back to that variable. Closures keep lexically-scoped variables (those created with my), but $_ isn't lexically scoped. That's the key to the difference between the two.

You could also solve the problem by forcing the anonymous sub to resolve $_ when it's created, using eval:

-command => eval "sub {print $_}"
(n.b. I haven't tested this and it might not be exactly right). But using closures is much easier, faster, and more elegant.

In reply to Re: Are we seeing syntax inconsistency? by sgifford
in thread Are we seeing syntax inconsistency? by TibetPerlMonk

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.