jeanluca has asked for the wisdom of the Perl Monks concerning the following question:

Dear Monks,

What is the best way to determine if a subroutine is called via an object or via the export (directly)
I thought that this could do the trick :
sub test { my ($self, $inp_hash_ref, ....) = @_ ; if ( ref($self) !~ /__PACKAGE__/ ) { $inp_hash_ref = $self ; ....... } } .....

Is this a good approach, if yes, how do I fix /__PACKAGE__/, because that doesn't work. I also tried:
/\Q__PACKAGE__\E/

Thanks in advance
Luca

Replies are listed 'Best First'.
Re: regexp and __PACKAGE__
by japhy (Canon) on Feb 14, 2006 at 16:05 UTC
    __PACKAGE__ is only special when used as a constant; putting it in a string (or a regex) makes it not a constant. While you could do ... =~ quotemeta(__PACKAGE__), this is not the issue. If you want to see if the first argument to your function is an object, I would suggest:
    sub something { if (eval { $_[0]->isa(__PACKAGE__) }) { # object call } else { # function call } }

    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
Re: regexp and __PACKAGE__
by brian_d_foy (Abbot) on Feb 14, 2006 at 16:46 UTC

    In general, you want your methods to be methods and your functions to not be methods. That way you don't have to worry about this. You might want to try something like File::Spec::Functions's method of currying method calls, or CGI's method of using a hidden object.

    You also shouldn't check if the object is in a particular package since you'll limit the ability of others to subclass your module.

    --
    brian d foy <brian@stonehenge.com>
    Subscribe to The Perl Review