Perl References
A reference is a pointer. A Perl reference is a scalar type that can point to variables, arrays, hashes (also called associative arrays), and even subroutines, and it can be used anywhere in the program.
Creating References
When defining a variable, prepend a \ to the variable name to get a reference to that variable, for example:
$scalarref = \$foo; # 标量变量引用 $arrayref = \@ARGV; # 列表的引用 $hashref = \%ENV; # 哈希的引用 $coderef = \&handler; # 子过程引用 $globref = \*foo; # GLOB句柄引用
In arrays, we can use anonymous array references, defined with []:
$aref= [ 1,"foo",undef,13 ];
The elements of an anonymous array can themselves be anonymous arrays, so we can use this method to construct arrays of arrays, and arrays of any dimension.
my $aref = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9],
]
In hashes, we can use anonymous hash references, defined with {}:
$href= { APR =>4, AUG =>8 };
We can also create an anonymous subroutine reference without a subroutine name:
$coderef = sub { print "Example!\n" };
Dereferencing
Dereferencing can be done using $, @, or % depending on the type, for example:
Examples
Executing the above example produces the following result:
10 为 : 10 1 2 3 为: 123 \%var 为 : key110key220
If you are not sure about the variable type, you can userefto determine it. The return values are as follows. If none of the following values apply, false is returned:
SCALAR ARRAY HASH CODE GLOB REF
Example:
Examples
Executing the above example produces the following result:
r 的引用类型 : SCALAR r 的引用类型 : ARRAY r 的引用类型 : HASH
Circular References
Circular references occur when two references contain each other. You need to use them carefully, otherwise it will cause memory leaks, as in the following example:
Examples
Executing the above example produces the following result:
Value of foo is : REF(0x9aae38)
Function References
Function reference format: \&
Calling a function reference format: & + the created reference name.
Example:
Examples
Executing the above example produces the following result:
元素 : age 元素 : 3 元素 : name 元素 : exampleOther Extensions