Objects with bless

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; } package main; my $c = Counter->new(start => 10); print ref($c), "\n";

perl demo.pl

Counter

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.

package Counter; use strict; use warnings; sub new { my ($class, %args) = @_; my $self = { count => $args{start} // 0 }; return bless $self, $class; } sub inc { my ($self) = @_; $self->{count}++; return $self->{count}; } package main; my $c = Counter->new(start => 10); print $c->inc(), "\n"; # 11

perl demo.pl

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.

package Counter; use strict; use warnings; sub new { my ($class, %args) = @_; my $self = { count => $args{start} // 0 }; return bless $self, $class; } sub count { my ($self, $value) = @_; $self->{count} = $value if defined $value; return $self->{count}; } package main; my $c = Counter->new(start => 10); $c->count(5); print $c->count(), "\n"; # 5

perl demo.pl

5

The defined check lets the setter accept 0, which a truth test would reject. This single pattern covers most small classes, and lesson 6.8 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.

package Counter; use strict; use warnings; sub new { my ($class, %args) = @_; my $self = { count => $args{start} // 0 }; return bless $self, $class; } sub inc { my ($self) = @_; $self->{count}++; return $self->{count}; } package main; my $c = Counter->new(start => 10); print "counter\n" if $c->isa("Counter"); print "can inc\n" if $c->can("inc");

perl demo.pl

counter
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.

package Temp; use strict; use warnings; sub new { my ($class, $path) = @_; open my $fh, ">", $path or die "open $path: $!"; return bless { fh => $fh, path => $path }, $class; } sub DESTROY { my ($self) = @_; close $self->{fh} if $self->{fh}; unlink $self->{path}; } package main; { my $tmp = Temp->new("/tmp/perl-destroy-demo.txt"); print "inside: ", -e $tmp->{path} ? "there" : "gone", "\n"; } print "outside: ", -e "/tmp/perl-destroy-demo.txt" ? "there" : "gone", "\n";

perl demo.pl

inside: there
outside: gone

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.

Questions

A new set of questions in a new order every time. Choose one answer for each, then check.

  1. What does bless do to a reference?

    Answer

    It attaches a package name, so method calls find their code through that package

    bless returns the same reference, marked with the class it belongs to, and that mark is what makes method lookup work.

  2. What is the first argument a method receives?

    Answer

    The object, or the class name when the method is a constructor

    A method call passes the invocant first: the blessed reference for $obj->method, the package name for Class->new.

  3. Why does the accessor test defined $value instead of if ($value)?

    Answer

    Because 0 is a valid value that a truth test would reject

    A setter must accept 0 and the empty string, and a truth test would turn both of them into a read.

  4. What is the difference between isa and can?

    Answer

    isa checks the class hierarchy, can checks whether the package has that method

    isa answers "is this object of that class or a subclass", and can returns the code reference of a method or undef.

  5. What does this program print? package Counter; sub new { bless { count => 0 }, shift } package main; my $c = Counter->new; print ref($c), "\n";

    Answer

    Counter

    A blessed reference reports the package it was blessed into, so ref gives the class name.

  6. What does this program print? package Counter; sub new { bless { count => 10 }, shift } sub inc { $_[0]->{count}++ } package main; my $c = Counter->new; $c->inc; $c->inc; print $c->{count}, "\n";

    Answer

    12

    Both calls increase the same hash entry, which started at 10.

  7. What does this program print? package Counter; sub new { bless { count => 10 }, shift } sub count { my ($self, $value) = @_; $self->{count} = $value if defined $value; return $self->{count}; } package main; my $c = Counter->new; $c->count(0); print $c->count, "\n";

    Answer

    0

    The defined test lets the setter store 0, so the read returns 0 rather than the old value.

  8. What does this program print? package Counter; sub new { bless {}, shift } sub inc { 1 } package main; my $c = Counter->new; print $c->isa("Counter") ? "isa\n" : "no isa\n"; print $c->can("dec") ? "can dec\n" : "no dec\n";

    Answer

    isa / no dec

    The object is a Counter, but the package has no method named dec, so can returns undef.

  9. What does this program print? package Temp; sub new { bless {}, shift } sub DESTROY { print "gone\n" } package main; { my $t = Temp->new; print "here\n"; } print "after\n";

    Answer

    here / gone / after

    The object is destroyed as the block ends, which is before the line after the block runs.

  10. A constructor forgets bless and returns a plain hash reference. What happens when the caller runs $obj->inc?

    Answer

    Perl stops with Can't call method "inc" on unblessed reference

    Method lookup needs the package the reference belongs to, and a plain hash reference has none.

Article author: Arthur Isaev