Perl教學 第12篇 Perl5中的引用之二
發表時間:2024-02-07 來源:明輝站整理相關軟件相關文章人氣:
[摘要]運行結果如下:$ test 1 2 3 4 Pointer Address of ARGV = ARRAY(0x806c378)Number of arguments : 40 : 1;1 : 2;2 : 3;3 : 4; 第5行將引用$pointer指向數組@ARGV,第6行輸出ARGV的地址。...
運行結果如下:
$ 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 = $pointer\n ";
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