Latest web development tutorials

Perl references

Reference is a pointer, Perl reference is a scalar type can point to variables, arrays, hash tables (also called associative arrays) or subroutine can be used anywhere in the program.


Create references

Defined variables, the variable name preceded by a \, we get a reference to the variable, such as:

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

In the array, we can use an anonymous array reference, use [] Definition:

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

Anonymous array elements can still be anonymous array, so we can use this method to construct an array of arrays, the array may be constructed of any dimension.

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

We can use a hash anonymous hash references, use {} definition:

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

We can not create a subroutine name anonymous subroutine reference:

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

Dereference

Cancel application can be used depending on the type of $, @ or%, to cancel, examples are 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";

Implementation of the above example the result is:

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

If you can not determine the variable type, you can use theref to determine the return value listed below, the following value is returned if there is no false:

SCALAR
ARRAY
HASH
CODE
GLOB
REF

Examples are 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";

Implementation of the above example the result is:

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

Circular references

Circular references cited in two mutually inclusive emergence. You need to be careful to use, otherwise it will lead to memory leaks, the following examples:

#!/usr/bin/perl

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

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

Implementation of the above example the result is:

Value of foo is : REF(0x9aae38)

Reference Functions

Function Reference format: \ &

Reference function call format: & + reference name created.

Examples are as follows:

#!/usr/bin/perl

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

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

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

Implementation of the above example the result is:

元素 : age
元素 : 3
元素 : name
元素 : w3big