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

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}); ...