Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How should I define 'static' subroutines in Perl?

I'm used to work in Java, so perhaps this question is a Java-oriented Perl question... anyway, I've created a Person package using Moose.

Now, I would like to add a few subroutines which are "static", that is, they do not refer to a specific Person, but are still closely related to Person package. For example, sub sort_persons gets an array of Person objects.

In Java, I would simply declare such functions as static. But in Perl... what is the common way to do that?

p.s. I think the Perlish terminology for what I'm referring to is "class methods".

like image 454
David B Avatar asked Oct 02 '10 12:10

David B


People also ask

What is subroutine in Perl explain passing agreements to subroutine?

Subroutines are blocks of code that can be reused across programs. They are the same as functions or user-defined functions in Perl. We can either define a subroutine in the same program or import it from another file using the use , do , or require statements.

How do you invoke a static method?

We can invoke a static method by using its class reference. An instance method is invoked by using the object reference.


1 Answers

There's no such thing as a static method in Perl. Methods that apply to the entire class are conventionally called class methods. These are only distinguished from instance methods by the type of their first argument (which is a package name, not an object). Constructor methods, like new() in most Perl classes, are a common example of class methods.

If you want a particular method to be invoked as a class method only, do something like this:

sub class_method {
    my ($class, @args) = @_;
    die "class method invoked on object" if ref $class;
    # your code        
} 
like image 178
Eugene Yarmash Avatar answered Sep 24 '22 22:09

Eugene Yarmash