perl 引用(一)

1. 普通变量引用 variable reference

   引用就好比C语言的指针,引用变量存储被引用变量的地址。赋值时注意要在变量前加上 \;使用时要多加一个 $ 。

   当然,引用也可以成为简单变量,可以使用引用的引用,使用时要记得多加一个$.引用也可以互相赋值

   

1 #!/usr/bin/perl  -w
2 my $variable="this is a reference test\n";
3 my $refv=\$variable;
4 my $refr=\$refv;
5 print "this is \$refv:$refv\n";
6 print "this is \$variable \$\$refv:$$refv";
7 print "this is reference's reference \$\$reference :$$refr\n";
8 print "this is \$variable \$\$\$refr:$$$refr";

D:\>perl reference.pl
this is $refv:SCALAR(0x468b20)
this is $variable $$refv:this is a reference test
this is reference's reference $$reference :SCALAR(0x468b20)
this is $variable $$$refr:this is a reference test

    

 

2. 数组变量引用 array reference

  数组引用跟变量引用一样

  

1 #!/usr/bin/perl  -w
2 my @array=qw/this is an array reference test/;
3 my $refa=\@array;
4 print "this is \@array[0]:$refa->[0]\n";
5 print "this is \@array[1]:$$refa[1]\n";
6 print "this is \@array use \@\$refa:@$refa\n";

使用一个元素 $$refa[n] 或者$refa->[n]

使用全部元素:@$refa

结果:

this is @array[0]:this
this is @array[1]:is
this is @array use @$refa:this is an array reference test

关于数组使用引用的好处 请参考:http://www.cnblogs.com/tobecrazy/archive/2013/06/11/3131887.html

3. 哈希变量引用 hash reference

哈希引用和变量引用数组引用一样,只需复制时加上\ ,使用时加上%

 

 1 #!/usr/bin/perl  -w
 2 my %hash=('a'=>"Hash",'b'=>"reference",'c'=>"test");
 3 my $refh=\%hash;
 4 print "this is \$\$refh:$$refh{'a'}\n";
 5 print "use whole hash with \%\$refh \n";
 6 foreach $key (keys %$refh)
 7 {
 8     print "$key => $$refh{$key}";
 9     print "\n";
10 }

%$refh 使用整个哈希

$$refh{$key} 使用一个hash 元素

运行结果:

this is $$refh:Hash
use whole hash with %$refh
c => test
a => Hash
b => reference

 

4. 匿名引用

        a.匿名变量

     $refva=\"this is anonymous variable\n";

        使用方法和变量引用一样,只需要$$refva

      b. 匿名数组 注意使用方括号[],使用方法同数组引用一样

       $refaa=[qw/this is anonymous array/];

  c. 匿名哈希 注意使用花括号 {},使用方法同hash引用

        $refha{'a'=>"Hash",'b'=>"reference",'c'=>"test" }

      

总结:

     1.引用赋值需要加\ ,使用时变量在引用变量前加$ ,数组加@ 哈希加%

     2.引用可以用在两个数组在函数中传递,避免数组被压缩成一个数组

     3.引用可以对匿名数组 变量 哈希使用

     4.引用可以创造perl结构体,使用二维数组(下一次总结)

posted @ 2013-06-24 16:48  to be crazy  阅读(785)  评论(0编辑  收藏  举报