Beefy Boxes and Bandwidth Generously Provided by pair Networks
XP is just a number
 
PerlMonks  

Re: Wrong package used when method and package have the same name

by japhy (Canon)
on May 02, 2006 at 14:09 UTC ( #546895=note: print w/replies, xml ) Need Help??


in reply to Wrong package used when method and package have the same name

Here is a much simpler case:
package DEF; sub new { bless [], shift } package ABC; sub new { bless {}, shift } sub DEF { "ABC's DEF function" } # still in package ABC! $x = new ABC; $y = new DEF; $z = new DEF::; print "X=$x\nY=$y\nZ=$z\n"; __END__ X=ABC=HASH(0x8151d6c) Y=ABC's DEF function=HASH(0x8151b44) Z=DEF=ARRAY(0x81525c4)
The problem is that, while in the ABC package, Perl sees new DEF as two function calls, not as an indirect object call. This is simply because of the order that Perl tries things in -- since it knows 'new' and 'DEF' are declared functions at that point, that's how it treats both of them. By using new DEF::, we force Perl to interpret it as an object call. Sadly, not even DEF->new will work, because Perl will try calling the "new" method of the package name returned by the DEF() function, "ABC's DEF function"!

Long story short, this is just how Perl parses your code. You shouldn't give functions and packages identical names. (Indirect object notation is smelly and should be avoided anyway.) To be foolproof, always append "::" to the end of your class names. DEF::->new and new DEF:: both behave properly in this case.


Jeff japhy Pinyan, P.L., P.M., P.O.D, X.S.: Perl, regex, and perl hacker
How can we ever be the sold short or the cheated, we who for every service have long ago been overpaid? ~~ Meister Eckhart

Replies are listed 'Best First'.
Re^2: Wrong package used when method and package have the same name
by kudra (Vicar) on May 02, 2006 at 14:27 UTC
    Thanks for the information. I guess I should not have called it a minimal test case but simply a reduced test case.

    Usually my method names would be lower-case and my package names ucfirst, so the situation would never come up. In this case I was attempting to replace an existing module and retain the same method names, which happened to use this a mixed case capitalization scheme. The duplicate names were introduced when I decided some of the data shouldn't really be stored in the original module, because multiple instances would need to be stored, and the logical name for the holding class was of course the same as the original method name...

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others contemplating the Monastery: (3)
As of 2021-12-06 06:40 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    R or B?



    Results (32 votes). Check out past polls.

    Notices?