in reply to Bizarre Results when Creating a Closure

You can do the closure without needing the explicit $icopy temp variable. Just write the code reference line like:

my $psub = [ sub { $chosen_idx = $_[0] }, $i ];

Replies are listed 'Best First'.
Re^2: Bizarre Results when Creating a Closure
by kyle (Abbot) on May 03, 2007 at 19:18 UTC

    That produces a reference to a list, not a code ref like the original. Instead of calling $psub->(), you have to write $psub->[0]->($psub->[1]) instead, and that works, but it sure is ugly.

      True, and perhaps I should have been a little clearer...

      The coderef in question is being used as a callback for a PerlTk widget, and a documented way to do closures for widget callbacks is to pass a reference to a list consisting of a coderef an anonymous sub as the first parameter followed by arguments.

      Reference "perldoc Tk::callbacks" or (Google) Tk::callbacks site:cpan.org

      Did you try actually running the code with the modification I proposed? It works exactly as expected.