Perl Quote
Reference is a pointer. Perl reference is a scalar type that can point to variables, arrays, hash tables (also called associative arrays) and even subroutines, and can be applied anywhere in the program.
Create a reference
When defining a variable, add \ in front of the variable name to get a reference to the variable, for example:
$scalarref = $foo; # 标量变量引用 $arrayref = \@ARGV; # 列表的引用 $hashref = \%ENV; # 哈希的引用 $coderef = \&handler; # 子过程引用 $globref = \*foo; # GLOB句柄引用
We can use anonymous array references in arrays, using [] definition:
$aref= [ 1,"foo",undef,13 ];
The elements of anonymous arrays can still be anonymous arrays, so we can use this method to construct an array of arrays , an array of any dimension can be constructed.
my $aref = [ [1, 2, 3], [4, 5, 6], [7, 8, 9], ]
In the hash we can use anonymous hash references, using {} definition:
$href= { APR =>4, AUG =>8 };
We can also create an anonymous subroutine reference without a subroutine name:
$coderef = sub { print "php!\n" };
Cancel reference
Cancellation of application can be canceled using $, @ or % according to different types. The example is as follows:
#!/usr/bin/perl $var = 10; # $r 引用 $var 标量 $r = $var; # 输出本地存储的 $r 的变量值 print "$var 为 : ", $$r, "\n"; @var = (1, 2, 3); # $r 引用 @var 数组 $r = \@var; # 输出本地存储的 $r 的变量值 print "@var 为: ", @$r, "\n"; %var = ('key1' => 10, 'key2' => 20); # $r 引用 %var 数组 $r = \%var; # 输出本地存储的 $r 的变量值 print "%var 为 : ", %$r, "\n";
The execution result of the above example is:
10 为 : 10 1 2 3 为: 123 %var 为 : key110key220
If you cannot determine the variable type, you can use ref to determine. The return value list is as follows. If there is no following value, return false:
SCALAR ARRAY HASH CODE GLOB REF
The example is as follows:
#!/usr/bin/perl $var = 10; $r = $var; print "r 的引用类型 : ", ref($r), "\n"; @var = (1, 2, 3); $r = \@var; print "r 的引用类型 : ", ref($r), "\n"; %var = ('key1' => 10, 'key2' => 20); $r = \%var; print "r 的引用类型 : ", ref($r), "\n";
The execution result of the above example is:
r 的引用类型 : SCALAR r 的引用类型 : ARRAY r 的引用类型 : HASH
Circular reference
Circular reference occurs when two references include each other. You need to use it carefully, otherwise it will cause memory leaks, as shown in the following example:
#!/usr/bin/perl my $foo = 100; $foo = $foo; print "Value of foo is : ", $$foo, "\n";
The execution result of the above example is:
Value of foo is : REF(0x9aae38)
Reference function
Function reference format: \&
Call reference function format: & + Created reference name.
The example is as follows:
#!/usr/bin/perl # 函数定义 sub PrintHash{ my (%hash) = @_; foreach $item (%hash){ print "元素 : $item\n"; } } %hash = ('name' => 'php', 'age' => 3); # 创建函数的引用 $cref = \&PrintHash; # 使用引用调用函数 &$cref(%hash);
The execution result of the above example is:
元素 : age 元素 : 3 元素 : name 元素 : php