in reply to coding a subroutine as both method and regular function

Leaving the debate aside for the moment whether this is a good idea in principle, your code as given doesn't support inheritance. When you test to see if you are called as a function or a method, you do
if ( ref $abs_path eq __PACKAGE__ ) {
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().

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

if ( Scalar::Util::blessed( $abs_path) ) {
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.

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

    I get most of what you're saying. Makes sense. Thank you so much for taking time to talk about this.

    It seems using code as both a procedural and an object oriented subroutine, could easily create problems. Perhaps this falls into the scope of 'clever', cute but .. just cute- that's all.

    I'm not going to be using this technique anymore, at least not until I understand better what it is really doing, maybe in a couple of years. Thank you.