Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl: the Markov chain saw
 
PerlMonks  

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

by jhourcle (Prior)
on Mar 25, 2005 at 03:51 UTC ( #442278=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 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__; ... }

Replies are listed 'Best First'.
Re: Answer: How do I make object methods callable as non-OO functions?
by cazz (Pilgrim) on Mar 25, 2005 at 15:27 UTC
    CGI.pm does something simliar, except with a generic sub.
    sub self_or_default { return @_ if defined($_[0]) && (!ref($_[0])) &&($_[0] eq 'CGI'); unless (defined($_[0]) && (ref($_[0]) eq 'CGI' || UNIVERSAL::isa($_[0],'CGI')) # slightl +y optimized for common case ) { $Q = $CGI::DefaultClass->new unless defined($Q); unshift(@_,$Q); } return wantarray ? @_ : $Q; }
    Then they use it like this:
    sub url_param { my ($self,@p) = self_or_default(@_); my $name = shift(@p); return undef unless exists($ENV{QUERY_STRING}); ...
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 avoiding work at the Monastery: (7)
As of 2016-09-01 02:46 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    The best thing I ever won in a lottery was:















    Results (439 votes). Check out past polls.