Beefy Boxes and Bandwidth Generously Provided by pair Networks
Pathologically Eclectic Rubbish Lister

Re: notabug quiz

by davido (Archbishop)
on Dec 12, 2003 at 09:56 UTC ( #314264=note: print w/replies, xml ) Need Help??

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).


Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://314264]
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others imbibing at the Monastery: (6)
As of 2018-05-23 15:46 GMT
Find Nodes?
    Voting Booth?