How can I write a Perl subroutine that works both as a normal subroutine or a class method?

perl

Solution

In general, there isn't. a `sub` is either written to be called as a method or it isn't.

See how File::Spec::Functions handles this situation by prepending the package name to the argument list.

Now, in a very specific, limited case, you can do:

shift if $_[0] eq __PACKAGE__;

as the first line in your sub to discard the first argument when the `sub` is called as a class method.

Problem

I'm writing a function that is mostly static in nature. I want to plug it into Template Toolkit, which passes along the class name. In essential, it is doing ``` ClassName->function( $args.. ) ``` but I want it to do something like ``` ClassName::function( $args.. ) ``` inside ``` sub function { } ``` what is the proper way to handle both cases?

Original source