perl 函数参数传递与返回值(一)
1.参数传递
普通模式:参数中没有数组和哈希
#!/usr/bin/perl -w use strict; sub getparameter { my $i; for( $i=0;$i<=$#_;$i++) { print "It's the "; print $i+1; print " parameter:$_[$i]\n"; } }
无论参数有多少个,均能正常传递。
调用函数
&getparameter($first,$second .. $end)
文艺模式:参数中包含数组
还是这个函数,只不过我们传递的参数里包括一个数组
#!/usr/bin/perl -w use strict; sub getparameter { my $i; for( $i=0;$i<=$#_;$i++) { print "It's the "; print $i+1; print " parameter:$_[$i]\n"; } } my @array=("this","is","a","test"); my $variable="this is another test"; #&getparameter(@array,$variable); &getparameter($variable,@array);
当我们只传入2个参数,一个数组,一个变量,结果是这样 ,变成了5个参数。无论数组在前还是在后,都是显示5个参数。 由此 @_ 会把数组每一个值当做一个参数储存。那我的疑问是perl能否正确的把传递的数组还原成数组而不是单个变量???
It's the 1 parameter:this is another test
It's the 2 parameter:this
It's the 3 parameter:is
It's the 4 parameter:a
It's the 5 parameter:test
那我们换一种方式接受参数:
#!/usr/bin/perl -w use strict; sub getparameter { (my @arr,my $var)=@_; print "It's the 1 parameter:@arr\n"; print "It's the 2 parameter:$var\n"; } my @array=("this","is","a","test"); my $variable="this is another test"; &getparameter(@array,$variable);
结果令人意外,$variable传递的参数丢失, 同时数组却取得所有参数,相当于把变量归为数组的一个元素。per了接受传递来的数组,会贪婪的把变量变成数组的元素。所以在接受参数传递赋值时,不要把数组放前面。
It's the 1 parameter:this is a test this is another test
Use of uninitialized value in concatenation (.) or string at test2.pl line 7.
It's the 2 parameter:
改成这样就好了:
#!/usr/bin/perl -w use strict; sub getparameter { (my $var,my @arr)=@_; print "It's the 1 parameter:$var\n"; print "Ti's the 2 parameter:@arr\n"; } my @array=("this","is","a","test"); my $variable="this is another test"; #&getparameter(@array,$variable); &getparameter($variable,@array);
运行结果:
It's the 1 parameter:this is another test
Ti's the 2 parameter:this is a test
如果要传递2个数组怎么办???
可以采用引用的方式
#!/usr/bin/perl -w use strict; sub getparameter { (my $arr1,my $arr2)=@_; print "It's the 1 parameter:@$arr1\n"; print "Ti's the 2 parameter:@$arr2\n"; } my @array1=("this","is","a","test"); my @array2=qw/this is another test/; #&getparameter(@array,$variable); &getparameter(\@array1,\@array2);
per了使用引用是在变量或数组前加\ ,相当于地址传递
所以运行结果是:
It's the 1 parameter:this is a test
Ti's the 2 parameter:this is another test

【推荐】国内首个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 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义