Methods in Perl

Perl supports methods defined on objects, which are typically blessed references to hash structures.

package Rect;
use strict;
use warnings;

sub new {
    my ($class, %args) = @_;
    return bless {
        width => $args{width},
        height => $args{height},
    }, $class;
}

# This 'area' method is defined for the Rect class
sub area {
    my $self = shift;
    return $self->{width} * $self->{height};
}

# Methods in Perl always receive the object as the first argument
sub perim {
    my $self = shift;
    return 2 * $self->{width} + 2 * $self->{height};
}

package main;
use strict;
use warnings;

my $r = Rect->new(width => 10, height => 5);

# Here we call the 2 methods defined for our Rect class
print "area: ", $r->area(), "\n";
print "perim: ", $r->perim(), "\n";

# In Perl, there's no distinction between calling methods on references or values
# All method calls are made using the arrow operator (->)
my $rp = $r;
print "area: ", $rp->area(), "\n";
print "perim: ", $rp->perim(), "\n";

To run the program:

$ perl rect.pl
area: 50
perim: 30
area: 50
perim: 30

In Perl, objects are typically implemented using blessed references to hash structures. The bless function is used to associate a reference with a package name, effectively creating an object.

Methods in Perl are simply subroutines defined within a package. They always receive the object (or class name for class methods) as their first argument, which is conventionally named $self.

Unlike Go, Perl doesn’t have a built-in distinction between value and pointer receivers. All method calls in Perl are made using the arrow operator (->), and the language handles the details of method dispatch.

Perl’s object system is quite flexible and allows for various object-oriented programming paradigms. However, it’s worth noting that more modern Perl code often uses object systems like Moose or Moo, which provide a more robust and feature-rich object-oriented programming experience.

Next, we’ll look at Perl’s mechanism for defining interfaces between objects, which is typically done using roles or abstract base classes.