Perl packages, bless, and inheritance

Perl builds objects from ordinary data. A package is a namespace, and a class is a package whose subroutines are methods. bless attaches a package name to a reference, usually a hash, which makes it an object of that class. A method call $obj->method passes the object as the first argument, conventionally named $self.

Perl
use strict;
use warnings;

package Animal;

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

sub name { return $_[0]{name} }
sub sound { return 'generic noise' }

sub speak {
    my $self = shift;
    return $self->name . ' says ' . $self->sound;
}

package Dog;
use parent -norequire, 'Animal';

sub sound { return 'Woof' }

sub speak {
    my $self = shift;
    return $self->SUPER::speak() . '!';
}

package main;

my @animals = (Animal->new(name => 'Generic'), Dog->new(name => 'Rex'));
print $_->speak, "\n" for @animals;
print $animals[1]->isa('Animal') ? "a Dog is an Animal\n" : "not an Animal\n";
print Dog->can('speak') ? "Dog can speak\n" : "Dog cannot speak\n";
print ref($animals[1]), "\n";
Read the full lesson