http://www.perlmonks.org?node_id=197960


in reply to Calling Madness

I am not entirely sure what you're asking, but I'll try to paraphrase:

Is there a way I can construct a package subroutine so that, regardless of whether:

it will do the Same Thing each time?

My answer: I think so. I'm not sure why you would want to do this, but it's the only thing I can see here.

Here's a method that would act that way (although it's not quite what you suggested). (untested):

package thisPack; sub smartish_sub { my $self; # for instance reference, if called that way my $class; # for classname, if called that way if (ref $_[0]) { if (UNIVERSAL::isa($self,'thisPack')) { # ( corrected from earlier ->isa call) # it's an instance method invocation my $self = shift @_; } # else it's not an instance, but it is a ref, so # it must be a fully-qualified invocation } else { # not a reference; ought to be class invocation my $class = shift; die "first argument to smartsub must be hashref\n" unless UNIVERSAL::isa($class, 'thisPack'); } # now any class- or instance- invocations have been # shifted off @_ my ($hash, $string) = @_; # might want error-checking here. print "$hash->{foo}\n$string"; } sub new { bless {}, shift; }

YMMV.

Updated (almost immediately): used UNIVERSAL::isa() everywhere, not ->isa().

second update: clarified package vs. class language.

Replies are listed 'Best First'.
Re: Re: Calling Madness
by Anonymous Monk on Sep 15, 2002 at 00:51 UTC
    You're on the right track :)

    See - this sub can be called by any method so I need to make sure everytime it's called I either shift off the package/class info or do nothing.

    My orgional code to do this (shift if ref $_[0] or $_[0] =~ /^PKG/;) doesn't work when your calling the sub by its fully-qualified "Package::method" name and $_[0] happens to be a hash ref.

    So maybe this will help in understanding my problem:

    shift if (ref $_[0] and $_[0]-is-the-ojbect-itself,-not-a-normal-hash-ref) or $_[0] =~ /^PKG/;