如何在 Perl 中访问函数参数?
在 C++ 中我会这样做:
void some_func(const char *str, ...);
some_func("hi %s u r %d", "n00b", 420);
在 PHP 中我会这样做:
function some_func()
{
$args = func_get_args();
}
some_func($holy, $moly, $guacomole);
How do I do that in Perl?
sub wut {
# What goes here?
}
In C++ I would do something like this:
void some_func(const char *str, ...);
some_func("hi %s u r %d", "n00b", 420);
In PHP I would do like this:
function some_func()
{
$args = func_get_args();
}
some_func($holy, $moly, $guacomole);
How do I do that in Perl?
sub wut {
# What goes here?
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您会这样做:
当您调用函数时,Perl 会自动填充特殊的
@_
变量。您可以通过多种方式访问它:@_
或其中的单个元素作为$_[0]
、$_[1]< /code>,等等,
通过将其分配给标量列表(或可能是散列,或另一个数组,或其组合):
请注意,在这种形式中,您需要将数组
@others
放在end,因为如果你把它放在前面,它会吞掉@_
的所有元素。换句话说,这不起作用:您还可以使用
shift
从@_
中提取值:请注意,
shift
将自动起作用如果您不为其提供参数,则在@_
上。编辑:您还可以通过使用哈希或哈希引用来使用命名参数。例如,如果您像这样调用
wut()
:...您可以执行以下操作:
这将是将命名参数引入到函数中的好方法,以便您可以稍后添加参数并您不必担心它们通过的顺序。
You would do:
Perl automatically populates the special
@_
variable when you call a function. You can access it in multiple ways:@_
or individual elements within it as$_[0]
,$_[1]
, and so onby assigning it to a list of scalars (or possibly a hash, or another array, or combinations thereof):
Note that in this form you need to put the array
@others
at the end, because if you put it in earlier, it'll slurp up all of the elements of@_
. In other words, this won't work:You can also use
shift
to pull values off of@_
:Note that
shift
will automatically work on@_
if you don't supply it with an argument.Edit: You can also use named arguments by using a hash or a hash reference. For example, if you called
wut()
like:...you could then do something like:
This would be a good way to introduce named parameters into your functions, so that you can add parameters later and you don't have to worry about the order in which they're passed.