Perl reference

A reference is a pointer, and a Perl reference is a scale type that can point to a variable, array, hash table (also known as an association array), or even a subroug that can be applied anywhere in the program.


Create a reference

When you define a variable, you get a reference to the variable by inglysing it before its name, such as:

$scalarref = \$foo;     # 标量变量引用
$arrayref  = \@ARGV;    # 列表的引用
$hashref   = \%ENV;     # 哈希的引用
$coderef   = \&handler; # 子过程引用
$globref   = \*foo;     # GLOB句柄引用

In an array, we can use an anonymous array reference, using the definition of :

$aref= [ 1,"foo",undef,13 ];

The elements of an anonymous array can still be anonymous arrays, so we can construct an array of arrays in this way, and we can construct an array of any dimension.

my $aref = [
        [1, 2, 3],
        [4, 5, 6],
        [7, 8, 9],
]

In a hash, we can use an anonymous hash reference to define it by using .

$href= { APR =>4, AUG =>8 };

We can also create an anonymous sub-program reference without a sub-program name:

$coderef = sub { print "W3CSchool!\n" };

De-reference

Cancellation apps can be canceled by using $, s, or % depending on the type, 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 result of executing the above instances is:

10 为 : 10
1 2 3 为: 123
%var 为 : key110key220

If you are not sure of the variable type, you can use ref to determine that the list of returned values is as follows and false is returned if the following values are not:

SCALAR
ARRAY
HASH
CODE
GLOB
REF

Here's an example:

#!/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 result of executing the above instances is:

r 的引用类型 : SCALAR
r 的引用类型 : ARRAY
r 的引用类型 : HASH

Loop reference

Loop references that contain each other in two references are appearing. You need to use it with care, otherwise it can lead to memory leaks, as in the following example:

#!/usr/bin/perl

my $foo = 100;
$foo = \$foo;

print "Value of foo is : ", $$foo, "\n";

The result of executing the above instances is:

Value of foo is : REF(0x9aae38)

Refers to a function

Function reference format:

Call the reference function format: the name of the reference created by the .

Here's an example:

#!/usr/bin/perl

# 函数定义
sub PrintHash{
   my (%hash) = @_;
   
   foreach $item (%hash){
      print "元素 : $item\n";
   }
}
%hash = ('name' => 'youj', 'age' => 3);

# 创建函数的引用
$cref = \&PrintHash;

# 使用引用调用函数
&$cref(%hash);

The result of executing the above instances is:

元素 : age
元素 : 3
元素 : name
元素 : youj