Beefy Boxes and Bandwidth Generously Provided by pair Networks
Do you know where your variables are?
 
PerlMonks  

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


Dave


Comment on Re: notabug quiz
Select or Download Code

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://314264]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others rifling through the Monastery: (9)
As of 2014-08-01 22:31 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    Who would be the most fun to work for?















    Results (50 votes), past polls