Objects with bless
| bless | |
| Methods | |
| Accessors | |
| isa and can | |
| DESTROY |
bless
An object in core Perl is a reference that knows which package it belongs to. The bless function attaches that package name, and from then on method calls find their code through it.
package Counter;
use strict;
use warnings;
sub new {
my ($class, %args) = @_;
my $self = { count => $args{start} // 0 };
return bless $self, $class;
}
1;
The constructor is an ordinary subroutine named new. It receives the class name as its first argument, builds a hash reference with the object state, and returns the blessed reference.
Methods
A method is a subroutine whose first argument is the object instead of the class. Everything else about it is normal Perl, so the same package can hold methods and plain functions.
sub inc {
my ($self) = @_;
$self->{count}++;
return $self->{count};
}
my $c = Counter->new(start => 10);
print $c->inc(), "\n"; # 11
The arrow is the same arrow you met with references. Perl looks up inc in the package that $c was blessed into, which is what makes polymorphism possible.
Accessors
Reaching into the hash from outside couples every caller to the internal layout. A pair of accessors fixes the interface: one method reads, the same method writes when given an argument.
sub count {
my ($self, $value) = @_;
$self->{count} = $value if defined $value;
return $self->{count};
}
$c->count(5);
print $c->count(), "\n"; # 5
The defined check lets the setter accept 0, which a truth test would reject. This single pattern covers most small classes, and lesson 34 replaces it with generated accessors.
isa and can
Two methods answer questions about an object before you call it. isa checks the class, including inherited ones, and can checks whether a method exists.
print "counter\n" if $c->isa("Counter");
print "can inc\n" if $c->can("inc");
Scalar::Util::blessed is the other half of the toolkit: it returns the package name for an object and undef for anything else, which is the safe way to validate an argument.
DESTROY
When the last reference to an object goes away, Perl calls its DESTROY method if one exists. That is where you close a socket or delete a temporary file, and it runs even when the program dies.
sub DESTROY {
my ($self) = @_;
close $self->{fh} if $self->{fh};
}
Do not rely on DESTROY for ordinary cleanup during a long run; scope the variable so the object disappears when the work ends. The method is a safety net, not a scheduler.
Next: Modern objects with Moo
Article author: Arthur Isaev