How can I write a Perl routine that works as a regular routine as well as a class method?

I am writing a function that is mostly static in nature. I want to connect it to the Template Toolkit, which goes by the name of the class. Essential what he does

ClassName->function( $args.. )

but I want him to do something like

ClassName::function( $args.. )

inside

sub function {
}

What is the correct way to handle both cases?

+3
source share
3 answers

In general, no. a is subeither written as a method to be called or not.

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

Now in a very specific limited case you can do:

shift if $_[0] eq __PACKAGE__;

, , sub .

+7

, Sinan , :

  • ClassName::function("ClassName")

:

if (@_ == $nArgsExpectedForThisFunc + 1) {
    $_[0] eq __PACKAGE__ || UNIVERSAL::isa($_[0], __PACKAGE__) || die;
    shift;
}

, ; , , , (, arrayref), .

+6

Template Toolkit , OO, . , .

Perl . , ( , , ) . :

ClassName::function('ClassName', @args);

. . .

package ClassName;

sub function {
    # do something
}

sub method {
    my $class = shift;
    function(@_);
}

. , File:: Spec , : OO .

+4

Source: https://habr.com/ru/post/1711185/


All Articles