in reply to i don't understand this scope behavior w/ closures and eval

As an optimisation, closures only capture the variables they need. Perl has no idea what variable you will need for an eval EXPR (since EXPR can evaluate to anything), so those can't be taken into consideration.

If Perl made a mistake (as it does in the second function), it will let you know with the warning "Variable "$var" is not available".

The workaround is to make Perl notice you need the variable (like you did in the third function). Adding $var if 0; is a cheap and simple way of doing that without introducing warnings.

Replies are listed 'Best First'.
Re^2: i don't understand this scope behavior w/ closures and eval
by ambrus (Abbot) on Feb 12, 2010 at 20:46 UTC

    Nitpick: I don't think of that as just an optimization, it's necessary for garbage collection so we don't have memory leaks and destructors are executed early.