Object-Oriented Perl
Classic Perl builds objects from three things you already know:
- A class is a package.
- An object is a reference (usually to a hash) that has been "blessed" into that package.
- A method is a sub in the package that receives the object as its first argument.
There is no special syntax beyond bless and the arrow ->, which makes the system simple and flexible. (Perl 5.38 added a new class keyword, covered in the next lesson.)
A first class
use strict;
use warnings;
package Counter;
sub new {
my ($class, %args) = @_;
my $self = { count => $args{start} // 0, step => $args{step} // 1 };
return bless $self, $class;
}
sub increment {
my ($self) = @_;
$self->{count} += $self->{step};
return $self;
}
sub value { $_[0]{count} }
package main;
my $c = Counter->new(start => 10, step => 5);
$c->increment;
$c->increment;
print "Value: ", $c->value, "\n";
print "Class: ", ref($c), "\n";
my $plain = Counter->new;
print "Default: ", $plain->increment->value, "\n";Value: 20
Class: Counter
Default: 1
Here is what happens:
Counter->new(...)callsCounter::new('Counter', start => 10, step => 5): the class name is passed as the first argument.bless $self, $classmarks the hash reference as belonging toCounter, and returns it.$c->incrementcallsCounter::increment($c): the object is passed as the first argument, conventionally named$self.- Returning
$selffromincrementallows method chaining:$plain->increment->value.
new is only a convention; a constructor can have any name.
Accessors
Code outside the class should use methods rather than poking into the hash. A common pattern is a combined getter/setter:
use strict;
use warnings;
package Product;
sub new {
my ($class, $name, $price) = @_;
die "price must be positive\n" unless $price > 0;
return bless { name => $name, price => $price }, $class;
}
sub name { $_[0]{name} }
sub price {
my ($self, $new) = @_;
if (defined $new) {
die "price must be positive\n" unless $new > 0;
$self->{price} = $new;
}
return $self->{price};
}
sub describe {
my ($self) = @_;
return sprintf "%s costs %.2f", $self->name, $self->price;
}
package main;
my $lamp = Product->new("Lamp", 24.99);
print $lamp->describe, "\n";
$lamp->price(19.5);
print $lamp->describe, "\n";
my $ok = eval { $lamp->price(-3); 1 };
print "Rejected: $@" unless $ok;Lamp costs 24.99
Lamp costs 19.50
Rejected: price must be positive
The setter validates input, which is one of the main reasons to use accessors at all. (eval and $@ are explained in the error-handling lesson.)
Class methods and class data
A method can be called on the class instead of an object. Class-wide data can be kept in a lexical variable at package level:
use strict;
use warnings;
package Ticket {
my $issued = 0; # shared by all Ticket objects
sub new {
my ($class, $event) = @_;
$issued++;
return bless { event => $event, number => $issued }, $class;
}
sub issued_count { $issued } # class method
sub label { my $s = shift; "#$s->{number} for $s->{event}" }
}
my @tickets = map { Ticket->new($_) } ("Concert", "Concert", "Theatre");
print $_->label, "\n" for @tickets;
print "Issued: ", Ticket->issued_count, "\n";#1 for Concert
#2 for Concert
#3 for Theatre
Issued: 3
Introspection: ref, isa and can
use strict;
use warnings;
use Scalar::Util qw(blessed);
package Dog { sub new { bless {}, shift } sub speak { "Woof" } }
my $rex = Dog->new;
print "ref: ", ref($rex), "\n";
print "blessed: ", blessed($rex), "\n";
print "blessed plain hash: ", (blessed({}) // "undef"), "\n";
print "isa Dog? ", ($rex->isa('Dog') ? "yes" : "no"), "\n";
print "can speak? ", ($rex->can('speak') ? "yes" : "no"), "\n";
print "can fly? ", ($rex->can('fly') ? "yes" : "no"), "\n";
my $method = "speak";
print "Dynamic call: ", $rex->$method, "\n";ref: Dog
blessed: Dog
blessed plain hash: undef
isa Dog? yes
can speak? yes
can fly? no
Dynamic call: Woof
can returns a code reference to the method (or false), and a method name stored in a variable can be called with $obj->$name.
Destructors
When the last reference to an object disappears, Perl destroys it immediately and calls its DESTROY method if it has one. This is useful for releasing resources:
use strict;
use warnings;
package Connection {
sub new { my ($c, $host) = @_; print "open $host\n"; bless { host => $host }, $c }
sub DESTROY { my $s = shift; print "close $s->{host}\n" }
}
{
my $db = Connection->new("db1");
print "working...\n";
} # $db goes out of scope here
print "after the block\n";open db1
working...
close db1
after the block
Test yourself
What does bless $ref, $class do?
- Copies the data into a new class
- Associates the reference with a package so methods can be called on it
- Makes the reference read-only
- Declares a class
In $obj->save(1), what is the first element of @_ inside save?
- 1
$obj- The class name string
- undef
What does Shape->new(3) pass to Shape::new?
(3)('Shape', 3)(bless {}, 3)- nothing