Beefy Boxes and Bandwidth Generously Provided by pair Networks
P is for Practical
 
PerlMonks  

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

( #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? 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__; ... }

Comment on Answer: How do I make object methods callable as non-OO functions?
Select or Download Code
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 chilling in the Monastery: (8)
As of 2015-07-28 10:10 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 (254 votes), past polls