Beefy Boxes and Bandwidth Generously Provided by pair Networks
Think about Loose Coupling

Re^3: shift vs @_

by jhourcle (Prior)
on Oct 03, 2006 at 15:05 UTC ( #576091=note: print w/replies, xml ) Need Help??

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;

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://576091]
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others studying the Monastery: (7)
As of 2017-12-12 22:39 GMT
Find Nodes?
    Voting Booth?
    What programming language do you hate the most?

    Results (340 votes). Check out past polls.