note
davido
Here is the spoiler for #1: <code>$x=0; { no strict 'refs'; my $x=42; my $y = 'x'; ok 1, ${$y} == 42; }</code><p>
This is an example of using symbolic references (which is why you had to put the <code>no strict 'refs'</code> part in.)
<p>
And to keep things straight, remember that the $x=0 piece of code is referring to a package global, whereas the <code>my $x=42;</code> 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.<p>
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.
<p>
This behavior is documented in [perlref]:
<p>
<blockquote>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.</blockquote><p>
And the POD even provides a similar example:
<p>
<code>
local $value = 10;
$ref = "value";
{
my $value = 20;
print $$ref;
}
__OUTPUT__
10
</code>
<p>
<div class="pmsig"><div class="pmsig-281137">
<br><p>Dave</p>
</div></div>
314238
314238