Book Home Programming PerlSearch this book

8.4. Symbolic References

What happens if you try to dereference a value that is not a hard reference? The value is then treated as a symbolic reference. That is, the reference is interpreted as a string representing the name of a global variable.

Here is how this works:

$name = "bam";
$$name = 1;                # Sets $bam
$name->[0] = 4;            # Sets the first element of @bam
$name->{X} = "Y";          # Sets the X element of %bam to Y
@$name = ();               # Clears @bam
keys %$name;               # Yields the keys of %bam
&$name;                    # Calls &bam

This is very powerful, and slightly dangerous, in that it's possible to intend (with the utmost sincerity) to use a hard reference, but to accidentally use a symbolic reference instead. To protect against that, you can say:

use strict 'refs';
and then only hard references will be allowed for the rest of the enclosing block. An inner block may countermand the decree with:
no strict 'refs';
It is also important to understand the difference between the following two lines of code:
${identifier};    # Same as $identifier.
${"identifier"};  # Also $identifier, but a symbolic reference.
Because the second form is quoted, it is treated as a symbolic reference and will generate an error if use strict 'refs' is in effect. Even if strict 'refs' is not in effect, it can only refer to a package variable. But the first form is identical to the unbracketed form, and will refer to even a lexically scoped variable if one is declared. The next example shows this (and the next section discusses it).

Only package variables are accessible through symbolic references, because symbolic references always go through the package symbol table. Since lexical variables aren't in a package symbol table, they are therefore invisible to this mechanism. For example:

our $value  = "global";
{
    my $value = "private";
    print "Inside, mine is ${value}, ";
    print "but ours is ${'value'}.\n";
}
print "Outside, ${value} is again ${'value'}.\n";
which prints:
Inside, mine is private, but ours is global.
Outside, global is again global.



Library Navigation Links

Copyright © 2002 O'Reilly & Associates. All rights reserved.