Beefy Boxes and Bandwidth Generously Provided by pair Networks
"be consistent"
 
PerlMonks  

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

( #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


Description:

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!
  • 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?
    Username:
    Password:

    What's my password?
    Create A New User
    Chatterbox?
    and the web crawler heard nothing...

    How do I use this? | Other CB clients
    Other Users?
    Others scrutinizing the Monastery: (12)
    As of 2015-07-03 12:26 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 (53 votes), past polls