in reply to shift vs @_
For example, this code could allow a function to act as a regular sub, or as a method (assuming the first argument will never be a reference unless it's called as a method):
my $self = ref $_[0] ? shift : undef; my($arg1,$arg2,$arg3)=@_;
Similarly, if you have a sub that takes a list as its final argument, shifting off the non-list arguments can make it clearer what you're doing, especially if you pass the list on to any other subs:
sub my_sort { my $sortname = shift; return sort $SORTS{$sortname} @_; }
This can also be useful if you decide to goto another sub, since that sub will see the modified @_ as its argument list.
Finally, as a matter of style, I usually get $self or $class with shift in methods and constructors, since it makes it clearer what the explicit arguments are, as compared to the implicit object reference or class name passed in as the first argument.
Update: Corrections and clarifications from jimt.
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: shift vs @_
by jimt (Chaplain) on Oct 02, 2006 at 19:54 UTC | |
by sgifford (Prior) on Oct 02, 2006 at 20:29 UTC | |
by jhourcle (Prior) on Oct 03, 2006 at 15:05 UTC | |
|
Re^2: shift vs @_
by Zadeh (Beadle) on Oct 02, 2006 at 21:05 UTC | |
by Tanktalus (Canon) on Oct 02, 2006 at 23:24 UTC | |
by Zadeh (Beadle) on Oct 03, 2006 at 19:35 UTC | |
by sgifford (Prior) on Oct 02, 2006 at 22:14 UTC | |
by Anonymous Monk on Oct 23, 2014 at 06:31 UTC | |
by Anonymous Monk on Oct 23, 2014 at 06:33 UTC | |
by chromatic (Archbishop) on Oct 03, 2006 at 02:03 UTC | |
by Anonymous Monk on Nov 12, 2010 at 02:47 UTC |