Symbolic References
Normally,
a construct such as $$var indicates that
$var is a reference variable, and the programmer
expects this expression to return the value that was pointed to by
$var when the references were taken.
What if $var is not a reference variable at all?
Instead of complaining loudly, Perl checks to see whether
$var contains a string. If so, it uses that string
as a regular variable name and messes around with this variable!
Consider the following:
$x = 10;
$var = "x";
$$var = 30; # Modifies $x to 30 , because $var is a symbolic
# reference !When evaluating $$var, Perl first checks to see
whether $var is a reference, which it is not;
it’s a string. Perl then decides to give the expression one
more chance: it treats $var’s contents as a
variable identifier ($x). The example hence ends
up modifying $x to 30.
It is important to note that symbolic references work only for global
variables, not for those marked private using my.
Symbolic references work equally well for arrays and hashes also:
$var = "x"; @$var = (1, 2, 3); # Sets @x to the enumerated list on the right
Note that the symbol used before $var dictates the
type of variable to access: $$var is equivalent to
$x, and
@
$var is equivalent to
saying
@
x.
This facility is immensely useful, and, for those who have done this
kind of thing before with earlier versions of Perl, is much more
efficient than using eval. Let us say you want
your script to process a command-line option such as
"-Ddebug_level=3" and set ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access