明輝手游網(wǎng)中心:是一個(gè)免費(fèi)提供流行視頻軟件教程、在線學(xué)習(xí)分享的學(xué)習(xí)平臺(tái)!

Perl教學(xué) 第12篇 Perl5中的引用之3

[摘要]與數(shù)組類似,通過引用訪問哈希表的元素形式為$$pointer{$index},當(dāng)然,$index是哈希表的鍵值,而不僅是數(shù)字。還有幾種訪問形式,此外,構(gòu)建哈希表還可以用=>操作符,可讀性更好些。下面再看一個(gè)例子:1 #!/usr/bin/perl2 #3 # Using Array refe...
與數(shù)組類似,通過引用訪問哈希表的元素形式為$$pointer{$index},當(dāng)然,$index是哈希表的鍵值,而不僅是數(shù)字。還有幾種訪問形式,此外,構(gòu)建哈希表還可以用=>操作符,可讀性更好些。下面再看一個(gè)例子:

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
結(jié)果輸出如下:

================== start test =================
$$pointer{$i} is Fri
${$pointer}{$i} is Fri
$pointer->{$i} is Fri
${$pointer{$i}} is
${$pointer->{$i}} is
================== end of test =================
 可以看到,前三種形式的輸出顯示了預(yù)期的結(jié)果,而后兩種則沒有。當(dāng)你不清楚是否正確時(shí),就輸出結(jié)果看看。在Perl中,有不明確的代碼就用print語句輸出來實(shí)驗(yàn)一下,這能使你清楚Perl是怎樣解釋你的代碼的。