Perl Reference

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.

Links to this page
  • Perl Variable

    Perl Variable could be defined in two scope: lexical and package. Lexical variables are like local variables in other languages, that is its lifetime end or get garbage collected when it is out of scope unless it is referenced#. They are defined by my keyword. Package variables are defined in the most recently declared namespace’s scope with the our keyword. It is sort of like a global variable that will live throughout the lifetime of the program. The following shows how to define a package variable:

  • Perl Hash

    Or with #Perl Reference using curly braces {}:

    Note: Be aware that Hash will be treated as list in other contexts such as Perl Array. Since there is no association between keys and values in a list, passing a Hash to an array will destroy the established relationship. One of the solution is to use #Perl Reference.

  • Perl Array

    We could also create an Array #Reference using square brackets []:

    Note: It is possible to combine two Arrays into an Array, but that Perl will not retain the container, that is the original owner of the data. This means there is no way to know who owns the data in the bigger Array. One of the solution to this is using #Perl Reference.

#perl #resource #)