in reply to coding a subroutine as both method and regular function
That won't do. If another class inherits from yours, it will have a different name but its objects have every right to call your method. Your code doesn't let them. The problem is similar to calling bless() with only one argument in new().if ( ref $abs_path eq __PACKAGE__ ) {
Elsewhere in the thread jdporter has mentioned the problem in passing:
I should also say that I don't know how well this will hold up under inheritance. You'd probably have to tweak certain things, i.e. rather than string test against __PACKAGE__, test using isa or can.
Using isa( __PACKAGE__) is a possibility. It will make inheritance work, but in the inheritance case it really does too much. The code has been called because the object "is a" __PACKAGE__ object by inheritance, so why check again?
There is also the possibility that the method was called fully qualified with an object of an arbitrary class, as in $obj->Your::Class::set_meta( ...). In this case, even the isa() test would reject what is a legitimate call. If the programmer thinks the object will support the method, she will probably know what she's doing.
So I suggest simply testing for object-ness
The discussion also shows how easy it is to break OO capabilites while adapting code so that methods can also be called as ordinary subs. I believe, if you want this capability you'd be better off with a pure OO class, plus an adapter module (possibly AUTOLOADER-driven) that arranges for calls-as-functions.if ( Scalar::Util::blessed( $abs_path) ) {
Anno
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: coding a subroutine as both method and regular function
by leocharre (Priest) on Mar 22, 2007 at 19:53 UTC |