views:

122

answers:

1

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".

+8  A: 

In perl class methods are not different from object methods. Both are just ordinary subroutines in some package. When a method is called as a class method, the first param contains the package name. That's what you can do:

package MyPkg;

sub class_method {
    my ($self, @params) = @_;
    die "used as an object method" if ref $self;
    # your code        
} 
eugene y
+1 I just "found" about it myself :) I guess the most common example is `new()` which I never thought of in terms of 'static' but it obviously is.
David B
Unless there's some reason why it would be bad for the class method to be called on an object, I would just skip checking `ref $self`.
cjm
To help distinguish class methods from object methods, I like to use `$class` as the variable that holds the invocant. So `sub class_method { my ($class, @params) = @_; # blah }`
daotoad