in reply to coding a subroutine as both method and regular function

I agree with Fletch, it's not a great idea in general. But in case you really need the inspiration, have a look how the venerable CGI module offers both an OO and a procedural interface. The basic pattern there is:
sub foo { my ($self, @args) = _self_or_default(@_); # continue coding OO-style }
I'll leave it to you to discover how hairy _self_or_default is.

Replies are listed 'Best First'.
Re^2: coding a subroutine as both method and regular function
by leocharre (Priest) on Mar 22, 2007 at 16:15 UTC

    In CGI.pm, that is a little bit wild. A lot of these sub call self_or_default()..

    Uhm.. I was gonna dissect how self_or_default() works.. but... ouch. It hurts. CGI.pm v 3.15 line 442:

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

    I mean, I get it.. it sees if the first list element is a ref or not, if it is a ref to 'CGI', it returns the list unchanged. If it is not.. then.. uhm... hmm.