However...

If you really want to check to see if the sub is being invoked as a method or a function, you can use the following:

#!/usr/bin/perl package myClass; use strict; use warnings; ### Pure-cheese useless constructor sub new { bless {}, __PACKAGE__ } ### Bimodal sub sub someFunction { my $self = shift if @_ && UNIVERSAL::isa( $_[0], 'UNIVERSAL' ); my $otherArg = shift; print "Called as ", defined $self ? "method" : "function", " with '$otherArg' argument.\n"; } package main; use strict; use warnings; # Invoked as a function myClass::someFunction( "function thingie" ); # Invoked as a method my $testThingie = new myClass; $testThingie->someFunction( "method thingie" ); # It even works invoked as a static method myClass->someFunction( "static method thingie" );


It basically just uses the mother of all superclasses ('UNIVERSAL') to check for object/class-ness. If a thing can be said to inherit from UNIVERSAL (have UNIVERSAL in its @ISA), then it can be assumed to be either a blessed reference (aka object), or the name of a class. What this function doesn't test is to see if the package that the first arg belongs to is actually your own. This is left as an excercise for the reader. =:)

Like Randal said, though: Once you venture down that path, your interface forever must support such nastiness, which can only lead to grief and ruin.


In reply to Re: so simple by Perlmage
in thread so simple by jettero

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.