目录
引用在C++这门语言用的非常多,很多场景下可以替代指针的作用。Perl也支持引用,属于一种标量类型,可以指向标量、数组、哈希和子程序等,可以看做就是指向其他对象的指针,我们可以通过引用来访问和修改它所指向的对象。
创建引用
Perl引用也用$来做声明,等号右边的对象前面加上\就可以。以数组和子程序为例:
$arrayRef = \@array;
$subRef1 = \&handler1; //handler1是子程序的名字
解引用
$A就是引用,前面加上这个应用所指类型的符号($,@,%,&)就可以对其解引用。比如$$scalarRef,@$arrayRef。
这种方式对数组和哈希解引用,打印出来发现是序列化的一串,但是我们仍然可以将它解引用后拷贝给另一个数组或者哈希对象,也可以通过在前面加上$($$hashRef{"name"} = "jack";)来访问和修改数组和哈希的某个元素。
子程序解引用(&$subRef1)会触发一次子程序调用。
ref($A)可以获取引用的具体类型,value有SCALAR、ARRAY、HASH、CODE等。
Demo
1 #!/usr/bin/perl -w
2 $scalar = 10;
3 @array = (1, 2, 3);
4 %hash = ('name'=>'hunk', 'age'=>25);
5 sub handler1{
6 print "handler1 be called.\n";
7 }
8
9 sub handler2{
10 print "handler2 be called.\n";
11 }
12
13 #get the reference of object
14 $scalarRef = \$scalar;
15 $arrayRef = \@array;
16 $hashRef = \%hash;
17 $subRef1 = \&handler1;
18 @subRef2 = (\&handler1, \&handler2);
19
20 #get the type and object of reference
21 print "=====CASE1=====\n";
22 print "scalar type: ", ref($scalarRef), " value:", $$scalarRef, "\n";
23 print "array type: ", ref($arrayRef), " value:", @$arrayRef, "\n";
24 print "array type: ", ref($hashRef), " value:", %$hashRef, "\n";
25 %hashObj1 = %$hashRef;
26 print "value of key name: ", $hashObj1{"name"}, "\n";
27 $hashObj1{"name"} = "jack";
28 print "value of key name: ", $hash{"name"}, "\n";
29 $$hashRef{"name"} = "jack";
30 print "value of key name: ", $hash{"name"}, "\n";
31
32 print "=====CASE2=====\n";
33 print "handler type: ", ref($subRef1), " value: ", &$subRef1, "\n";
34 print "---------------\n";
35 foreach $handler (@subRef2){
36 &$handler();
37 }
Output:
[root@izuf682lz6444cynn96up0z basic]# ./reference.pl
=====CASE1=====
scalar type: SCALAR value:10
array type: ARRAY value:123
array type: HASH value:namehunkage25
value of key name: hunk
value of key name: hunk
value of key name: jack
=====CASE2=====
handler1 be called.
handler type: CODE value: 1
---------------
handler1 be called.
handler2 be called.
匿名对象
可以通过引用创建匿名对象。特别的,匿名数组的元素可以是匿名数组,所以可以创建任意维度的匿名数组,并且多维数组支持下标访问子数组。
1 #!/usr/bin/perl -w
2 $arrayRef1 = [11, 22, 33];
3 $arrayRef2 = [
4 [1, 2, 3],
5 [4, 5, 6],
6 ];
7 $hashRef = {'name'=>'hunk', 'age'=>25};
8 $subRef = sub {print "sub be called.\n"};
9
10 print $$arrayRef1[2], "\n";
11 print @$arrayRef2, "\n";
12 print @$arrayRef2[1], "\n";
13 print $$arrayRef2[1][1], "\n";
14 print $$hashRef{'name'}, "\n";
15 &$subRef;
[root@izuf682lz6444cynn96up0z basic]# ./reference.pl
33
ARRAY(0x248bff0)ARRAY(0x248c128)
ARRAY(0x248c128)
5
hunk
sub be called.
引用的引用
1 #!/usr/bin/perl -w
2 $var = 100;
3 $varRef = \$var;
4 $varRefRef = \$varRef;
5 print "value: ", $$varRef, "\n";
6 print "value: ", $varRef, "\n";
7 print "value: ", $$varRefRef, "\n";
[root@izuf682lz6444cynn96up0z basic]# ./reference.pl
value: 100
value: SCALAR(0x1e54740)
value: SCALAR(0x1e54740)