Perl 的移位与@_ 的子程序参数赋值有区别吗? [英] Is there a difference between Perl's shift versus assignment from @_ for subroutine parameters?

查看:22
本文介绍了Perl 的移位与@_ 的子程序参数赋值有区别吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

让我们暂时忽略 Damian Conway 对于任何给定子程序不超过三个位置参数的最佳实践.

Let us ignore for a moment Damian Conway's best practice of no more than three positional parameters for any given subroutine.

以下两个示例在性能或功能方面有什么区别吗?

Is there any difference between the two examples below in regards to performance or functionality?

使用shift:

sub do_something_fantastical {
    my $foo   = shift;
    my $bar   = shift;
    my $baz   = shift;
    my $qux   = shift;
    my $quux  = shift;
    my $corge = shift;
}

使用@_:

sub do_something_fantastical {
    my ($foo, $bar, $baz, $qux, $quux, $corge) = @_;
}

假设两个示例在性能和功能方面都相同,那么人们对一种格式有何看法?显然,使用 @_ 的示例代码行更少,但使用 shift 不是更清晰,如另一个示例所示?欢迎提出有理有据的意见.

Provided that both examples are the same in terms of performance and functionality, what do people think about one format over the other? Obviously the example using @_ is fewer lines of code, but isn't it more legible to use shift as shown in the other example? Opinions with good reasoning are welcome.

推荐答案

存在功能差异.shift 修改了 @_,以及来自 @_ 没有.如果您之后不需要使用 @_ ,那么这种差异对您来说可能无关紧要.我尝试总是使用列表分配,但有时我会使用 shift.

There's a functional difference. The shift modifies @_, and the assignment from @_ does not. If you don't need to use @_ afterward, that difference probably doesn't matter to you. I try to always use the list assignment, but I sometimes use shift.

但是,如果我从 shift 开始,就像这样:

However, if I start off with shift, like so:

 my( $param ) = shift;

我经常创建这个错误:

 my( $param, $other_param ) = shift;

那是因为我不经常使用 shift,所以我忘记到作业的右侧将其更改为 @_.这就是不使用 shift 的最佳实践的要点.我可以像您在示例中所做的那样为每个 shift 制作单独的行,但这很乏味.

That's because I don't use shift that often, so I forget to get over to the right hand side of the assignment to change that to @_. That's the point of the best practice in not using shift. I could make separate lines for each shift as you did in your example, but that's just tedious.

这篇关于Perl 的移位与@_ 的子程序参数赋值有区别吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆