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?
The use of
shiftto 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.The results on perl 5.8.8 on my machine:
Not dramatic, but there it is. Always test your scenario on your version of perl on your target hardware to find out for sure.
shiftis also useful in cases where you want to shift off the invocant and then call aSUPER::method, passing the remaining@_as-is.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%argshash or expecting a single hash reference argument) is a much better approach.