Using Hard References
Just as there are numerous ways to create references, there are also several ways to use, or dereference, a reference. There is just one overriding principle: Perl does no implicit referencing or dereferencing.[4] When a scalar is holding a reference, it always behaves like a simple scalar. It doesn't magically start being an array or hash or subroutine; you have to tell it explicitly to do so, by dereferencing it.
Using a Variable as a Variable Name
When you encounter a scalar like
$foo, you should be thinking "the scalar value of
foo." That is, there's a foo
entry in the symbol table, and the $ funny
character is a way of looking at whatever scalar value might be
inside. If what's inside is a reference, you can look inside
that (dereferencing $foo) by
prepending another funny character. Or looking at it the other way
around, you can replace the literal foo in
$foo with a scalar variable that points to the
actual referent. This is true of any variable type, so not only is
$$foo the scalar value of whatever
$foo refers to, but @$bar is
the array value of whatever $bar refers to,
%$glarch is the hash value of whatever
$glarch refers to, and so on. The upshot is that
you can put an extra funny character on the front of any simple
scalar variable to dereference it:
$foo = "three humps"; $scalarref = \$foo; # $scalarref is now a reference to $foo $camel_model = $$scalarref; # $camel_model is now "three humps"
Here are some other dereferences:
$bar = $$scalarref; ...
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