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

Get Programming Perl, 3rd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.