http://www.perlmonks.org?node_id=314264


in reply to notabug quiz

Here is the spoiler for #5: $x=1; { my $x=2; sub x {eval '$x'} } { my $x=3; ok 5, x }

In the POD for eval we see that expressions (contained in quotes) are compiled and evaluated at runtime, whereas code blocks are put to bed at compiletime.

So walk through what's going on here....

The "my $x=2" is a lexically scoped scalar, contained in the same lexical block as the eval. eval '$x'; refers to that $x, because the sub in which the eval exists is defined inside the same lexical scope as that particular $x. If we weren't using 'eval', it would be a no-brainer that the $x that the sub sees is the one that is equal to 2.

The my $x=3 exists within a different lexical block, and has nothing to do with x(), because x() was compiled in a lexical block where $x=3 couldn't be seen.

What gets confusing is the issue of reference counting, and runtime compilation. When the block in which $x=2 is defined ends, the eval '$x' hasn't yet been evaluated. Thus, when the block ends, the reference count for that $x drops to zero, it falls out of scope, and disappears. Then later on, x() is called, and the eval is executed. It tries to access the $x that has already dissappeared from existance, and ends up with an undefined value.

At first I had to wonder why the package global version of $x wasn't being seen from within the eval instead. But that's easy; it was masked by the lexical $x=2 at the time the sub was compiled.

This code essentially represents a closure, but as ysth later commented, "Perl doesn't realize it's a closure until it's too late." (thanks for the puzzles, ysth).


Dave