处理Perl子程序参数是否“移位"有害? [英] Is 'shift' evil for processing Perl subroutine parameters?

查看:129
本文介绍了处理Perl子程序参数是否“移位"有害?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我经常使用shift来解压缩功能参数:

I'm frequently using shift to unpack function parameters:

sub my_sub {
    my $self = shift;
    my $params = shift;
    ....
}

但是,我的许多同事都在宣扬shift实际上是邪恶的.您能解释一下为什么我更喜欢

However, many on my colleagues are preaching that shift is actually evil. Could you explain why I should prefer

sub my_sub {
    my ($self, $params) = @_;
    ....
}

shift?

推荐答案

使用shift来解压缩参数并不是邪恶的.这是一个常见的约定,并且可能是处理参数的最快方法(取决于有多少个参数以及如何传递它们).这是一个有些常见情况的示例,就是这种情况:一个简单的访问器.

The use of shift to unpack arguments is not evil. It's a common convention and may be the fastest way to process arguments (depending on how many there are and how they're passed). Here's one example of a somewhat common scenario where that's the case: a simple accessor.

use Benchmark qw(cmpthese);

sub Foo::x_shift { shift->{'a'} }
sub Foo::x_ref   { $_[0]->{'a'} }
sub Foo::x_copy  { my $s = $_[0]; $s->{'a'} }

our $o = bless {a => 123}, 'Foo';

cmpthese(-2, { x_shift => sub { $o->x_shift },
               x_ref   => sub { $o->x_ref   },
               x_copy  => sub { $o->x_copy  }, });

我的机器上在perl 5.8.8上的结果:

The results on perl 5.8.8 on my machine:

            Rate  x_copy   x_ref x_shift
x_copy  772761/s      --    -12%    -19%
x_ref   877709/s     14%      --     -8%
x_shift 949792/s     23%      8%      --

不引人注目,但确实如此.始终在目标硬件上的perl版本上测试您的方案,以确保确定.

Not dramatic, but there it is. Always test your scenario on your version of perl on your target hardware to find out for sure.

shift在想要移开主诉对象然后调用SUPER::方法并按原样传递其余@_的情况下也很有用.

shift is also useful in cases where you want to shift off the invocant and then call a SUPER:: method, passing the remaining @_ as-is.

sub my_method
{
  my $self = shift;
  ...
  return $self->SUPER::my_method(@_);
}

但是,如果在函数顶部有很长的my $foo = shift;操作序列,我可能会考虑使用@_的批量复制.但是总的来说,如果您有一个函数或方法需要多个参数,则使用命名参数(例如,将所有@_捕获在%args哈希中或期望使用单个哈希引用参数)会更好.方法.

If I had a very long series of my $foo = shift; operations at the top of a function, however, I might consider using a mass copy from @_ instead. But in general, if you have a function or method that takes more than a handful of arguments, using named parameters (i.e., catching all of @_ in a %args hash or expecting a single hash reference argument) is a much better approach.

这篇关于处理Perl子程序参数是否“移位"有害?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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