We could create a reference to a variable (could be Perl Array# or Perl Hash#) by using \
syntax such as follows:
my $var = "hi";
my $refToVar = \$var;
print $refToVar; # Output: SCALAR(0x812e6ec) or something similar
As shown, a Reference will be Autovivified# into string, which means that it can’t point to a string as it is a string itself. If it is evaluated, it will always return true#. To dereference it, we could add an extra $
to the reference:
# with scalar variable
my $derefRefToVar = ${$refToVar}; # or
my $derefRefToVar = $$refToVar; # if there's no ambiguity
print $derefRefToVar; # Output: "hi"
# array or hash
my $hashRef->{key} += 5 # hash
my $arrayRef->[1] = 'red' # array
Note: There is a library call Data::Dumper
that could take any types and print it in a human-readable form. This is quite useful when printing a structure such as an array and a hash.
We could deep copy a data structure from a Reference using the function dclone()
imported from Storable
module (with use Storable dclone
).
A referent (referenced #Perl Variable) will not be garbage collected once out of scope. This means that the variable is still alive in the memory but it can’t be accessed via name (variable name). Instead, it should be referred with the corresponding reference name.