A reference is a pointer. A Perl reference is a scalar type that can point to a variable, array, hash table (also called an associative array) or even a subroutine, and can be applied anywhere in the program.
When defining a variable, add in front of the variable name to get a reference to the variable, for example:
$scalarref = $foo; # Scalar variable reference $arrayref = @ARGV; # List reference $hashref = %ENV; # Hash reference $coderef = &handler; # Subroutine reference $globref = *foo ; # GLOB handle reference
We can use anonymous array references in arrays, using [] definition:
$aref= [ 1,"foo",undef,13 ];
The elements of an anonymous array can still be an anonymous array, so we can use this method to construct an array of arrays, and we can construct an array of any dimension.
my $aref = [ [1, 2, 3], [4, 5, 6], [7, 8, 9],]
In hashes we can use anonymous hash references, defined using {}:
$href= { APR =>4, AUG =>8 };
We can also create an anonymous subroutine reference without a subroutine name:
$coderef = sub { print "Codercto!n" };
Dereference can be canceled using $, @ or % according to different types. Examples are as follows:
The result of executing the above example is:
10 is: 101 2 3 is: 123%var is: key110key220
If you are not sure of the variable type, you can use ref to determine it. The return value list is as follows. If there is no following value, it returns false:
SCALARARRAYHASHCODEGLOBREF
Examples are as follows:
The result of executing the above example is:
Reference type of r: SCALAR Reference type of r: ARRAYr Reference type: HASH
A circular reference occurs when two references contain each other. You need to use it carefully, otherwise it will cause memory leaks, as in the following example:
The result of executing the above example is:
Value of foo is : REF(0x9aae38)
Function reference format: &
The format of calling the reference function: & + the created reference name.
Examples are as follows:
The result of executing the above example is:
element: age element: 3 element: name element: codercto