PERL / CHAPTER 12

Blessed references and method receivers

Advanced

Understand object dispatch without hiding the underlying data.

By the end of this chapter

  • Construct an object by blessing a reference
  • Trace the invocant passed to a method
  • Protect invariants through the public API

The idea

A conventional Perl object is a reference associated with a package by bless. Method lookup uses that package, while the referenced data stores instance state. Calling a method with arrow syntax passes the invocant as the first argument, so a method commonly extracts $self before its remaining parameters. A class-method constructor receives the class name in that position.

A blessed hash is still accessible as a hash reference, so API discipline matters if callers could bypass invariants by changing fields directly. Keep public operations small and document what they may mutate. Test two independent instances and aliasing of one instance separately. Object-oriented syntax does not automatically copy data or prevent shared references between records.

Perl example
use strict; use warnings;
{ package Counter;
  sub new { my ($class)=@_; bless {n=>0},$class }
  sub next { my ($self)=@_; return ++$self->{n} }
}
my $c=Counter->new();
print $c->next()," ",$c->next(),"\n";
Result
1 2

The constructor blesses a fresh hash, and each method call receives that object as its first argument.

Try it yourself

Add a checked decrement operation that cannot make a counter negative.

Use your own editor for this exercise. Runnable challenges on CodeQuest are available for JavaScript, Python, and SQL.

CHECK YOUR UNDERSTANDING

Chapter checkpoint

In $object->method(3), what is the method’s first argument?