读书人

perl脚本引述和指针

发布时间: 2012-10-08 19:54:56 作者: rapoo

perl脚本——引用和指针
一、使用反斜线(\)操作符
反斜线操作符与C语言中传递地址的操作符&功能类似。一般是用\创建变量又一个新的引用。下面为创建简单变量的引用的例子:
$variavle = 22;
$pointer = \$variable;
$ice = "jello";
$iceprt = \$ice;
引用$pointer指向存有$variable值的位置,引用$iceptr指向"jello"。即使最初的引用$variable销毁了,仍然可以通过$pointer访问该值,这是一个硬引用,所以必须同时销毁$pointer和$variable以便该空间释放到内存池中。
在上面的例子中,引用变量$pointer存的是$variable的地址,而不是值本身,要获得值,形式为两个$符号,如下:

    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是怎样解释你的代码的。

读书人网 >perl python

热点推荐