David B
David B

Reputation: 30008

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

Upvotes: 17

Views: 5766

Answers (2)

Jeff
Jeff

Reputation: 1

Perl in 2025 has a module called Object::Pad see: https://metacpan.org/pod/Object::Pad

This is a precursor to future Perl built-in OO. Some of the design history is here: https://github.com/Ovid/Corinna

With Object::Pad you mark a method with the :common attribute to give it CLASS scope. As noted above this is slightly different from STATIC but used practically in the same way.

#!/usr/bin/perl
use v5.36;    # say, strict, warnings, signatures
use Object::Pad;

class Point {
    our $howmany = 0;

    field $x :param :reader;
    field $y :param :reader;

    ADJUST {
        $Point::howmany++;
    }

    # CLASS method
    method being_used :common () {
        return $howmany;
    }
}

my $a = Point->new( x => 0, y => 0);
my $b = Point->new( x => 1, y => 1);

# Call the class method
say "Points in use: ", Point->being_used;
# 2

Upvotes: 0

Eugene Yarmash
Eugene Yarmash

Reputation: 150011

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        
} 

Upvotes: 20

Related Questions