http://www.perlmonks.org?node_id=576091


in reply to Re^2: shift vs @_
in thread shift vs @_

First of all, there's the fact that this won't operate properly if it's called as a class method such as Some::Package->foo( qw(arg1 arg2 arg3) ); $_[0] is a string, in that case.

Secondly, it breaks down if you pass in a normal reference as your first argument. foo({'hashkey' => 'hashval'}, qw(arg4 arg5)); You end up setting a normal arrayref as $self.

I can get around some of those problems. First, if we assume that the subroutine was written as a function originally, and had no concept of self:

    shift if UNIVERSAL::isa ($_[0], __PACKAGE__);

We can also deal with the possibility that we need self for the class name (eg, incase soemone calls it as a method to override inherited routines, but there's still existing code that has code that assumes it's a function:

my $self = __PACKAGE__; $self = shift if UNIVERSAL::isa ($_[0], __PACKAGE__);

It completely handles your first issue, however, this will break if you have a method that takes as its first argument an item of its same type (and someone tries calling it as a function), or if someone does some sort of multiple inheritance, that results in the first argument inheriting from this class (and then calls it as a function). It also adds an additional problem case where a function argument that's a string containing the name of a package that inherits the package in question is assumed to be the 'Class->method()' syntax..

Child->test(); package Parent; sub test { my $self = __PACKAGE__; $self = shift if UNIVERSAL::isa ($_[0], __PACKAGE__); print "Package name : $self\n"; } package Child; use base Parent;