Is 'shift' evil for processing Perl subrou

2019-02-02 21:12发布

I'm frequently using shift to unpack function parameters:

sub my_sub {
    my $self = shift;
    my $params = 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) = @_;
    ....
}

to shift?

8条回答
欢心
2楼-- · 2019-02-02 22:17

I don't think shift is evil. The use of shift shows your willingness to actually name variables - instead of using $_[0].

Personally, I use shift when there's only one parameter to a function. If I have more than one parameter, I'll use the list context.

 my $result = decode($theString);

 sub decode {
   my $string = shift;

   ...
 }

 my $otherResult = encode($otherString, $format);

 sub encode {
   my ($string,$format) = @_;
   ...
 }
查看更多
欢心
3楼-- · 2019-02-02 22:17

There is an optimization for list assignment.

The only reference I could find, is this one.

5.10.0 inadvertently disabled an optimization, which caused a measurable performance drop in list assignment, such as is often used to assign function parameters from @_ . The optimisation has been re-instated, and the performance regression fixed.

This is an example of the affected performance regression.

sub example{
  my($arg1,$arg2,$arg3) = @_;
}
查看更多
登录 后发表回答