Last Updated: February 25, 2016
·
1.296K
· glitchmr

Perl classes template

My previous templaste for JavaScript already got two upvotes, so I've wrote second template for language where classes also could be confusing for classical object-oriented programming users - Perl.

The Perl OOP is very flexible behind the scenes - it supports multiple inheritance (enough rope to hang yourself) which could be altered in any moment (actually, rope is too long), calling methods which don't exist (using AUTOLOAD sub), dynamic adding of properties (*Animal::DESTROY = sub {}), operator overloading (see overload pragma for details). For simplicity, those features aren't discussed, but you can find those in Perl documentation.

use strict;
use warnings;
# say function
use 5.010;

# Class Animal
package Animal {
    sub new {
        # You should always use current class to help
        # inheritance.
        my ($class, $name) = @_;
        # Constructor
        my $self = {};
        $self->{name} = $name;
        # In Perl, objects are references to Perl data
        # structures which were associated with a
        # particular class.
        return bless $self, $class;
    }
    sub move {
        my $self = shift;
        my ($meters) = @_;
        say "$self->{name} moved ${meters}m.";
    }
}

# Class Snake
package Snake {
    # Following statement would be needed if class is
    # Animal.pm (it should be, but to make example simpler
    # it isn't).
    # use Animal;

    # List of objects from which Snake inherits. Can be
    # modified dynamically.
    our @ISA = qw( Animal );
    sub move {
        # $self needs to be shifted to avoid two objects in
        # arguments when calling SUPER (usually not what
        # you want).
        my $self = shift;

        say "Slithering...";
        $self->SUPER::move(@_);
    }
}

# use Snake;

# Don't type "new Snake", this syntax works only because of
# Indirect Object Syntax. Don't use this feature as it
# could be easily broken.
# http://perldoc.perl.org/perlobj.html#Indirect-Object-Syntax
Snake->new('Sammy the Python')->move(5);

If you still find this template too confusing, many Perl programmers made various OO systems to make OOP programming easier.