Beefy Boxes and Bandwidth Generously Provided by pair Networks
Don't ask to ask, just ask

Re: notabug quiz

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

in reply to notabug quiz

Here is the spoiler for #1: $x=0; { no strict 'refs'; my $x=42; my $y = 'x'; ok 1, ${$y} == 42; }

This is an example of using symbolic references (which is why you had to put the no strict 'refs' part in.)

And to keep things straight, remember that the $x=0 piece of code is referring to a package global, whereas the my $x=42; piece of code is creating a lexical scalar. The lexical is a different entity than the package global. Within the {...} block, the global $x is pretty much hidden by the lexical $x of the same name. And when everyone plays nice and avoids symbolic references, that's usually the behavior we see and expect; lexical scoping masking variables of the same name from broader-scoped blocks, and the broader-scoped lexicals (or globals) being protected from whatever the more narrowly scoped entities of the same name are doing.

But when you play with symbolic refs, you have to remember that the symbolic reference always refers to the package global, which in the example, equals 0, not 42.

This behavior is documented in perlref:

Only package variables (globals, even if localized) are visible to symbolic references. Lexical variables (declared with my()) aren't in a symbol table, and thus are invisible to this mechanism.

And the POD even provides a similar example:

local $value = 10; $ref = "value"; { my $value = 20; print $$ref; } __OUTPUT__ 10


Replies are listed 'Best First'.
Re: Re: notabug quiz
by Enlil (Parson) on Dec 12, 2003 at 09:39 UTC
    There is also a quip about this in perlfaq7:How can I access a dynamic variable while a similarly named lexical is in scope? .


Re^2: notabug quiz
by Aristotle (Chancellor) on Dec 12, 2003 at 09:35 UTC
    And while more elaborate, the same applies, of course, to test #5. Ugh, I misread the test - too used to Test::More semantics.

    Makeshifts last the longest.

Log In?

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

How do I use this? | Other CB clients
Other Users?
Others browsing the Monastery: (4)
As of 2016-10-21 01:09 GMT
Find Nodes?
    Voting Booth?
    How many different varieties (color, size, etc) of socks do you have in your sock drawer?

    Results (284 votes). Check out past polls.