Beefy Boxes and Bandwidth Generously Provided by pair Networks
Syntactic Confectionery Delight

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 quiet...

How do I use this? | Other CB clients
Other Users?
Others romping around the Monastery: (7)
As of 2017-11-24 15:34 GMT
Find Nodes?
    Voting Booth?
    In order to be able to say "I know Perl", you must have:

    Results (350 votes). Check out past polls.