Beefy Boxes and Bandwidth Generously Provided by pair Networks
good chemistry is complicated,
and a little bit messy -LW
 
PerlMonks  

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;


Comment on Re^3: shift vs @_
Select or Download Code

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://576091]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others imbibing at the Monastery: (6)
As of 2015-07-04 18:17 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    The top three priorities of my open tasks are (in descending order of likelihood to be worked on) ...









    Results (60 votes), past polls