This should be easy, but I don't remember seeing in the docs. What's the most elegant way of having methods support being called as both a package method and as a class/object method?

In a method without arguments, it's pretty easy since there will be either no argument, or the first argument (self) will be ignored:

package MyPackage; sub foo() { print 'stuff'; } 1; MyPackage::foo(); MyPackage->foo();

However, when I go to add argument to foo(), I'm not quite sure what the safest way is to see how the method was called.

package MyPackage; sub foo() { my $self = shift; my $text; if (ref($self) eq __PACKAGE__) { $text = shift; } else { $text = $self; }; print $text; }; 1; MyPackage::foo('stuff'); MyPackage->foo('stuff');

Now, checking the ref($self) works, but if I inherit and override this package, self could be many things.

I suspect there is some ->can, ->isa, and ref() magic involved, but I just haven't stumbled on it yet. I think the Digest::MD5 module works this way.

Yes, I know there are probably no good reasons to do this, other than some people like to use OOP, and some don't. I figure why not impliment both styles and let end users decide, and learn something new along the way.

-=Chris


In reply to Methods supporting both package and OOP style calls by jk2addict

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.