jk2addict has asked for the wisdom of the Perl Monks concerning the following question:
This should be easy, but I don't remember seeing in the docs. What's the most elegant way of having methods support being called as both a package method and as a class/object method?
In a method without arguments, it's pretty easy since there will be either no argument, or the first argument (self) will be ignored:
package MyPackage; sub foo() { print 'stuff'; } 1; MyPackage::foo(); MyPackage->foo();
However, when I go to add argument to foo(), I'm not quite sure what the safest way is to see how the method was called.
package MyPackage; sub foo() { my $self = shift; my $text; if (ref($self) eq __PACKAGE__) { $text = shift; } else { $text = $self; }; print $text; }; 1; MyPackage::foo('stuff'); MyPackage->foo('stuff');
Now, checking the ref($self) works, but if I inherit and override this package, self could be many things.
I suspect there is some ->can, ->isa, and ref() magic involved, but I just haven't stumbled on it yet. I think the Digest::MD5 module works this way.
Yes, I know there are probably no good reasons to do this, other than some people like to use OOP, and some don't. I figure why not impliment both styles and let end users decide, and learn something new along the way.
-=Chris
|
---|