perl--匿名数据

前端之家收集整理的这篇文章主要介绍了perl--匿名数据前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

在C里,间接的最常见的形式就是指针,它可以让一个变量保存另外一个变量的内存地址。

在Perl里,间接的最常见的形式是引用。

什么是引用?

在我们的例子里,$vitals[0] 的值是”john”.

也就是说它正好包含另外一个(全局)变量的名字,我们说第一个变量提到了第二个变量,

并且这种参考叫符号引用,因为Perl必须在一个符号表找出@john 来才到能找到它。

8.2 创建引用

创建引用的方法有好多种,我们在讲述它们的时候大多数先描述它们,然后才解释如何使用(解引用)所生成的引用。

8.2.1 反斜杠操作符

你可以用一个反斜杠创建一个指向任何命名变量或者子过程的引用。(

你还可以把它用于一个匿名标量值,比如7或”camel”,尽管你通常并不需要这些东西)乍一看,这个操作符的作用类似

C里的&(取址)操作符

[root@master Webqq]# cat t12.pl
$scalarred = \$foo;

$constref = \186_282.42;

$arrayref = \@ARGV;

$hashref = \%ENV;

$coderef = \&handler;

print “$scalarred is $scalarred\n”;

print “$constref is $constref\n”;

print “$arrayref is $arrayref\n”;

[root@master Webqq]# perl t12.pl
scalarredisSCALAR(0x10b4470) constref is SCALAR(0x1097e38)
$arrayref is ARRAY(0x10b4068

8.2.2.1 匿名数组组合器

你可以用方括号创建一个指向匿名属组的引用:

$arrayref = [1,2,[‘a’,’b’,’c’,’d’]];

[root@master Webqq]# cat t13.pl
arrayref=[1,2,[a,b,c,d]];print arrayref->[2][2]\n”;

[root@master Webqq]# perl t13.pl
c

2维数组,第2列数组的第3个元素

现在我们有一个方法来表示我们本章开头的表:

[root@master Webqq]# cat t13.pl

table=[[join,47,brown,186]@H_403_399@,[@H_275_403@“mary,23,hazel,128],[bill,35,blue,157]];print table->[0][1];
print table>[1][1];print table->[2][1];
[root@master Webqq]# perl t13.pl
472335[root@master Webqq]#

8.2.2.2 匿名散列组合器

你可以用花括号创建一个指向匿名散列的引用:

[root@master Webqq]# cat t14.pl
hashref=Ada@H_404_627@m=>Eve,Clyde=>$bonnie,Antony=>Cleo.patra;print hashref;
print “\n”;
print $$hashref{Antony};

[root@master Webqq]# perl t14.pl
HASH(0x20f6d48)
Cleopatra[root@master Webqq]#
[root@master Webqq]#

[root@master Webqq]# cat t15.pl
table=john=>[47,brown,186],mary=>@H_403_953@[23,hazel,128],bill=>[35,blue,157],;print table;
print “\n”;
print

tablejohn[1];print
table{john}[2];
[root@master Webqq]# perl t15.pl
HASH(0x18c9710)
brown186[root@master Webqq]#

这是一个数组散列,选择最好的数据结构是难度很高的工种,下一章专门讲这个。

下面介绍散列的散列

[root@master Webqq]# cat t16.pl
table=john=>@H_403_1176@age=>47,eyes=>brown,weight=>186,,mary=>age=>23,eye@H_984_1301@s=>hazel,weight=>128,,bill=>age=>35,eyes@H_371_1403@=>blue,weight=>157,,;pr@H_502_1455@int table;
print “\n”;
print $$table{john}{age};
[root@master Webqq]# perl t16.pl
HASH(0xe696a8)
47[root@master Webqq]#

8.2.2.3 匿名子过程组合器

你可以通过不带子过程名字的sub创建一个匿名子过程

[root@master Webqq]# cat t17.pl
coderef = sub { print "Boink!\n" }; # 现在 &coderef 打印 “Boink!”
print &$coderef;
[root@master Webqq]# perl t17.pl
Boink!
1[root@master Webqq]#

&$$coderef; 子程序解引用

猜你在找的Perl相关文章