Beefy Boxes and Bandwidth Generously Provided by pair Networks
Keep It Simple, Stupid

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

by cosimo (Hermit)
on Jun 30, 2004 at 12:09 UTC ( #370742=categorized answer: print w/replies, xml ) Need Help??

Q&A > object-oriented programming > How do I make object methods callable as non-OO functions? - Answer 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) :-)

Log In?

What's my password?
Create A New User
and all is calm...

How do I use this? | Other CB clients
Other Users?
Others chanting in the Monastery: (5)
As of 2018-02-22 02:00 GMT
Find Nodes?
    Voting Booth?
    When it is dark outside I am happiest to see ...

    Results (288 votes). Check out past polls.