子例程中的默认参数值 [英] Default argument values in subroutines
本文介绍了子例程中的默认参数值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
sub hello {
print @_ || 你好,世界;
}
如果你需要的只是一个参数,你将如何为多个参数设置默认值?我打算这样做:
sub hello {
my $ say = $ _ [0] || 你好;
my $ to = $ _ [1] || 世界!;
打印$ say $ to;
}
但是这需要很多工作......必须有一个更简单的方法;可能是最佳做法?感谢!
解决方案
我使用如下所示的命名参数完成它:
sub hello {
my(%arg)=(
'foo'=>'default_foo',
'bar'=>'default_bar ',
@_
);
}
我相信 Params :: Validate 支持默认值,但这比我喜欢的要麻烦。
I have been working with perl for about two months now; it just occurred to me that I don't know how to set default arguments for subroutines. Here is what I considered:
sub hello {
print @_ || "Hello world";
}
And that works fine for if all you needed was one argument. How would you set default values for multiple arguments? I was going to do this:
sub hello {
my $say = $_[0] || "Hello";
my $to = $_[1] || "World!";
print "$say $to";
}
But that's a lot of work... There must be an easier way; possibly a best practice? Thanks!
解决方案
I do it with named arguments like so:
sub hello {
my (%arg) = (
'foo' => 'default_foo',
'bar' => 'default_bar',
@_
);
}
I believe Params::Validate supports default values, but that's more trouble than I like to take.
这篇关于子例程中的默认参数值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文