in reply to Doubly-nested deeply bound variable is undefined

It appears that perl does not see the use of $x in foo, and thus does not close foo on $x. But once you put in the "print $x" there, it does close foo on $x, and then the anonymous sub can close on the same $x.

One workaround would be:

use strict; use warnings; sub run_this { shift->() } { my $x = "hello\n"; sub foo { { no warnings; $x } run_this( sub { print $x; }); } } foo();
Note the useless use of $x in a void context, which gets masked away with the no warnings bit. It does the same as yours as far as the problem is concerned (forcing perl to close foo on $x), but with no side effects going to standard-out ;-)

Replies are listed 'Best First'.
Re^2: Doubly-nested deeply bound variable is undefined
by asokoloski (Sexton) on Nov 14, 2006 at 19:06 UTC
    Exactly. I guess my question is, why doesn't the use of $x inside the anonymous sub tell foo() that it needs to close over $x? Is this a bug in the perl interpreter?

    And by the way, thanks for all the answers everyone. I have the feeling that there's really no satisfying way to solve this at this time :) The workarounds are helpful, though.

      Yes, it's a bug in Perl 5.8. Dave Mitchell fixed it in bleadperl, so the code works correctly in Perl 5.9.3 and later (maybe 5.9.2).

        Awesome, now I can sleep at night. Thanks :)