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, known
as a sigil, 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 sigil. 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 sigil 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;
push(@$arrayref, $filename);
$$arrayref[0] = "January"; # Set the first element of @$arrayref
@$arrayref[4..6] = qw/May June July/; # Set several elements of @$arrayref
%$hashref = (KEY => "RING", BIRD => "SING"); # Initialize whole hash
$$hashref{KEY} = "VALUE"; # Set one key/value pair
@$hashref{"KEY1","KEY2"} = ("VAL1","VAL2"); # Set two more pairs
&$coderef(1,2,3);
say $handleref "output";This form of dereferencing can only make use of ...
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