Where you mostly went wrong, I think, was in only pushing to @Sel and not popping from it. In other words, if you clicked on a checkbox, you'd push its value to @Sel; and if you clicked it again to deselect it, you'd just push again. The list would grow longer and longer, and things would not work as intended.

Meanwhile, this:

-command => sub{push(@Sel, $n)} && sub{ $Selected[$i] = defined $Selec +ted[$i] ? undef : $n;}

most likely will not do what you may think; although you can use the && operator on anonymous subroutine references (they're scalars, after all), they'll always be a true value, and the operator will return the last value evaluated, in this case the second reference (see C style Logical And in perlop). So the above line is really equivalent to

-command => sub{ $Selected[$i] = defined $Selected[$i] ? undef : $n;}

Now, this IS fairly close to what I wrote, of course, but:

I got around the latter by introducing a new variable inside the loop that holds the current value of $i; this goes out out of scope at the end of the loop body, so in the next loop iteration, a new variable with the same name is created, and each anonymous subroutine sees a different variable, one that keeps the right value of $i. (It's worth noting that even though the variables go out of scope, their duration does not end, as they're still visible to the anonymous subroutines.)

This is perhaps a little difficult to wrap your head around at first. For more information on scope and duration, I'd recommend Mark Dominus's Higher Order Perl (available as a free PDF here, or a dead-tree edition here), pp. 71-76.


In reply to Re^3: reset checkbutton value by AppleFritter
in thread reset checkbutton value by amboxer21

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.