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. 數(shù)組變量引用 array reference
? 數(shù)組引用跟變量引用一樣
??
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
結(jié)果:
this is @array[0]:this
this is @array[1]:is
this is @array use @$refa:this is an array reference test
關(guān)于數(shù)組使用引用的好處 請參考:http://www.cnblogs.com/tobecrazy/archive/2013/06/11/3131887.html
3. 哈希變量引用 hash reference
哈希引用和變量引用數(shù)組引用一樣,只需復(fù)制時加上\ ,使用時加上%
?
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 元素
運行結(jié)果:
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. 匿名數(shù)組 注意使用方括號[],使用方法同數(shù)組引用一樣
? ? ? ?$refaa=[qw/this is anonymous array/];
c. 匿名哈希 注意使用花括號 {},使用方法同hash引用
? ? ? ? $refha{'a'=>"Hash",'b'=>"reference",'c'=>"test"?}
? ? ??
總結(jié):
? 1.引用賦值需要加\ ,使用時變量在引用變量前加$ ,數(shù)組加@ 哈希加%
2.引用可以用在兩個數(shù)組在函數(shù)中傳遞,避免數(shù)組被壓縮成一個數(shù)組
3.引用可以對匿名數(shù)組 變量 哈希使用
?4.引用可以創(chuàng)造perl結(jié)構(gòu)體,使用二維數(shù)組(下一次總結(jié))
《新程序員》:云原生和全面數(shù)字化實踐50位技術(shù)專家共同創(chuàng)作,文字、視頻、音頻交互閱讀總結(jié)
以上是生活随笔為你收集整理的perl 引用(一)的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 三步找出牛股技法
- 下一篇: 《程序员修炼之道》备忘清单