学习perl应当铭记:Perl中的数组和哈希表始终是一维的。
因此,数组和哈希表只保存标量值,不直接存贮数组或其它的复杂数据结构。数组的成员要么是数(或字符串)要么是引用。
对数组和哈希表可以象对简单变量一样使用反斜线操作符,数组的引用如下:
1 #!/usr/bin/perl
2 #
3 # Using Array references
4 #
5 $pointer = @ARGV;
6 printf "n Pointer Address of ARGV = $pointern";
7 $i = scalar(@$pointer);
8 printf "n Number of arguments : $i n";
9 $i = 0;
10 foreach (@$pointer) {
11 printf "$i : $$pointer[$i++]; n";
12 }
运行结果如下:
$ test 1 2 3 4
Pointer Address of ARGV = ARRAY(0x806c378)
Number of arguments : 4
0 : 1;
1 : 2;
2 : 3;
3 : 4;
第5行将引用$pointer指向数组@ARGV,第6行输出ARGV的地址。$pointer返回数组第一个元素的地址,这与C语言中的数组指针是类似的。第7行调用函数scalar()获得数组的元素个数,该参数亦可为@ARGV,但用指针则必须用@$pointer的形式指定其类型为数组,$pointer给出地址,@符号说明传递的地址为数组的第一个元素的地址。第10行与第7行类似,第11行用形式$$pointer[$i]列出所有元素。
对关联数组使用反斜线操作符的方法是一样的--把所有关联数组名换成引用$poniter。注意数组和简单变量(标量)的引用显示时均带有类型--ARRAY和SCALAR,哈希表(关联数组)和函数也一样,分别为HASH和CODE。下面是哈希表的引用的例子。
#!/usr/bin/perl
1 #
2 # Using Associative Array references
3 #
4 %month = (
5 '01', 'Jan',
6 '02', 'Feb',
7 '03', 'Mar',
8 '04', 'Apr',
9 '05', 'May',
10 '06', 'Jun',
11 '07', 'Jul',
12 '08', 'Aug',
13 '09', 'Sep',
14 '10', 'Oct',
15 '11', 'Nov',
16 '12', 'Dec',
17 );
18
19 $pointer = %month;
20
21 printf "n Address of hash = $pointern ";
22
23 #
24 # The following lines would be used to print out the
25 # contents of the associative array if %month was used.
26 #
27 # foreach $i (sort keys %month) {
28 # printf "n $i $$pointer{$i} ";
29 # }
30
31 #
32 # The reference to the associative array via $pointer
33 #
34 foreach $i (sort keys %$pointer) {
35 printf "$i is $$pointer{$i} n";
36 }
结果输出如下:
$ mth
Address of hash = HASH(0x806c52c)
01 is Jan
02 is Feb
03 is Mar
04 is Apr
05 is May
06 is Jun
07 is Jul
08 is Aug
09 is Sep
10 is Oct
11 is Nov
12 is Dec
与数组类似,通过引用访问哈希表的元素形式为$$pointer{$index},当然,$index是哈希表的键值,而不仅是数字。还有几种访问形式,此外,构建哈希表还可以用=>操作符,可读性更好些。下面再看一个例子:
1 #!/usr/bin/perl
2 #
3 # Using Array references
4 #
5 %weekday = (
6 '01' => 'Mon',
7 '02' => 'Tue',
8 '03' => 'Wed',
9 '04' => 'Thu',
10 '05' => 'Fri',
11 '06' => 'Sat',
12 '07' => 'Sun',
13 );
14 $pointer = %weekday;
15 $i = '05';
16 printf "n ================== start test ================= n";
17 #
18 # These next two lines should show an output
19 #
20 printf '$$pointer{$i} is ';
21 printf "$$pointer{$i} n";
22 printf '${$pointer}{$i} is ';
23 printf "${$pointer}{$i} n";
24 printf '$pointer->{$i} is ';
25
26 printf "$pointer->{$i}n";
27 #
28 # These next two lines should not show anything 29 #
30 printf '${$pointer{$i}} is ';
31 printf "${$pointer{$i}} n";
32 printf '${$pointer->{$i}} is ';
33 printf "${$pointer->{$i}}";
34 printf "n ================== end of test ================= n";
35
结果输出如下:
================== start test =================
$$pointer{$i} is Fri
${$pointer}{$i} is Fri
$pointer->{$i} is Fri
${$pointer{$i}} is
${$pointer->{$i}} is
================== end of test =================
可以看到,前三种形式的输出显示了预期的结果,而后两种则没有。当你不清楚是否正确时,就输出结果看看。在Perl中,有不明确的代码就用print语句输出来实验一下,这能使你清楚Perl是怎样解释你的代码的。