Beefy Boxes and Bandwidth Generously Provided by pair Networks
Your skill will accomplish
what the force of many cannot
 
PerlMonks  

Re: Calling Madness

by jkahn (Friar)
on Sep 15, 2002 at 00:35 UTC ( #197960=note: print w/ replies, xml ) Need Help??


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:

  • I call it as an instance method
  • I call it as a packageclass method
  • I call it by its fully-qualified Pack::method name
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.


Comment on Re: Calling Madness
Select or Download Code
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/;

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://197960]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others about the Monastery: (7)
As of 2015-08-01 03:02 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    The top three priorities of my open tasks are (in descending order of likelihood to be worked on) ...









    Results (285 votes), past polls