本文主要介绍Perl的复杂数据结构,包括:
- 二维数组
- 哈希结构及复杂哈希结构
二维数组
Perl的数组由一对圆括号及用逗号分隔的元素组成(当然还有其他的声明方式)。
如:@array = ("apple","orange","pear");
二维数组声明方式有两种:
- @array = ([1,2,3],[4,5,6],[7,8,9]);这种方式中@array表示数组,如左图。
- $ref_array = [[1,2,3],[4,5,6],[7,8,9]];这种方式中$array表示数组的引用,如右图。
两种声明方式没有太大差别。最终都得到了一个二维数组。针对这两种声明方式,同时也有两种数组读取方式。
- $array[0][0];直接操作数组,指代第一个数组中第一个元素。
- $ref_array->[0][0];由于第二种方式是引用数组,所以使用“->”进行读取,读取的结果同上。
- 由于数组的内部仍是引用,所以两种方法的引用方式还可以写成:$array[0]->[0]和$ref_array->[0]->[0].
Perl使用push函数向数组中新增元素。
perldoc文档关于push方法的说明
C:\>perldoc -f push push ARRAY,LIST push EXPR,LIST Treats ARRAY as a stack by appending the values of LIST to the 把数组当做一个栈,将LIST列表值追加到数组的尾部。 end of ARRAY. The length of ARRAY increases by the length of 数组的长度根据LIST列表的长度进行增加。 LIST. Has the same effect as 和下面程序的作用一样,但是效率更高。 for $value (LIST) { $ARRAY[++$#ARRAY] = $value; } but is more efficient. Returns the number of elements in the 返回推送完成后数组的长度。 array following the completed "push". Starting with Perl 5.14, "push" can take a scalar EXPR, which 从Perl5.14开始,push方法允许标量作为参数,标量必须是一个数组的引用。 must hold a reference to an unblessed array. The argument will 参数将被自动指向引用 be dereferenced automatically. This aspect of "push" is push的这个特性是实验性的,可能在未来的版本中被改变。 considered highly experimental. The exact behaviour may change in a future version of Perl. To avoid confusing would-be users of your code who are running earlier versions of Perl with mysterious syn