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

How do I make object methods callable as non-OO functions?

by trammell (Priest)
on Jun 24, 2004 at 21:34 UTC ( #369493=categorized question: print w/replies, xml ) Need Help??
Contributed by trammell on Jun 24, 2004 at 21:34 UTC
Q&A  > object-oriented programming


For example, say I have a class 'Foo' that is used thusly:
use Foo; my $f = Foo->new(%args); my $g = $f->frobnicate;
but for some Very Good Reason, we want to be able to call it in a more procedural fashion:
use Foo 'frobnicate'; my $g = frobnicate($args);
Is there a good way of doing this? Is there a good reason not to do this?

Answer: How do I make object methods callable as non-OO functions?
contributed by jhourcle

I use the following at the beginning of the sub, so I can still use $self, and someone can override the functions in a derived class, if need be. (it won't work with your exact calling syntax though, as it's mostly for items that don't require values from the actual object).

sub function_name { # for a function call my $self = __PACKAGE__; # for a method call $self = shift if UNIVERSAL::isa( $_[0], __PACKAGE__ ); ... }

You could also write do the shorter, more efficient, but potentially more confusing :

sub function_name { my $self = UNIVERSAL::isa( $_[0], __PACKAGE__ ) ? shift : __PACKAGE__; ... }
Answer: How do I make object methods callable as non-OO functions?
contributed by cosimo

Probably, what you want is something like:

package Foo; sub new { # A noop constructor bless {}, shift; } sub frobnicate { my($self, @args) = @_; unless($self eq 'Foo' || (ref $self && $self->isa('Foo'))) { unshift @args, $self; undef $self; } # Now $self is available only if you have an OO call # List of @args is always the same return join(', ', @args). "\n"; }
and use it in the following way:
my $f = Foo->new(); print $f->frobnicate('my','args'); # or print Foo::frobnicate('my','args'); # or even print Foo->frobnicate('my','args');
Beware, though that doing something like $self->isa('Foo') breaks inheritance mechanisms and IMHO it is a Bad Thing (tm).

As usual, perl "gives you enough rope to hang yourself", which is a Good Thing (tm) :-)

Answer: How do I make object methods callable as non-OO functions?
contributed by Anonymous Monk

use Exporter; @ISA = ('Exporter'); @EXPORT = @EXPORT_OK = qw(frobnicate);
frobnicate is then available both as an OO-subroutine and a procedural one...

Please (register and) log in if you wish to add an answer

  • 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, 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, 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.
  • Log In?

    What's my password?
    Create A New User
    and not a whimper to be heard...

    How do I use this? | Other CB clients
    Other Users?
    Others avoiding work at the Monastery: (4)
    As of 2018-06-23 10:06 GMT
    Find Nodes?
      Voting Booth?
      Should cpanminus be part of the standard Perl release?

      Results (125 votes). Check out past polls.