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结构体,使用二维数组(下一次总结)

【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义