对于子例程参数,Perl的移位与@@的赋值之间是否有区别? [英] Is there a difference between Perl's shift versus assignment from @_ for subroutine parameters?

查看:73
本文介绍了对于子例程参数,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天全站免登陆