Objects with bless

Contents
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

Related articles
Perl
Perl course: zero to hero in 50 lessons
What is Perl and where it runs
Install Perl and check the version
Your first Perl script
The debugger as a REPL
Scalars and sigils
Numbers
Strings
Interpolation and quoting
Arrays
push, pop, shift and splice
Hashes
keys, values, exists and delete
Scalar and list context
Conditions and comparison
while, for, next and last
foreach and the default variable
Subroutines
Arguments in @_
References
Nested data structures
Regular expressions: match and anchors
Captures and named groups
Substitution with s///
split and join
grep and map
Sort and the Schwartzian transform
Read and write files
File tests and metadata
Directories and paths
die, warn and eval
Modules and Exporter
CPAN and cpanm
Objects with bless
Modern objects with Moo
Testing with Test::More
strict, warnings and diagnostics
Options with Getopt::Long
Environment and %ENV
system, backticks and pipes
One-liners with -n and -p
CSV and TSV processing
JSON with JSON::PP
HTTP clients with HTTP::Tiny
Sockets and IO::Socket
Databases with DBI
Capstone: todo CLI
Capstone: log report
Performance and profiling
Modern Perl tour
Hero roadmap: the whole course on one page
Install Perl on Windows 11
Install Perl on Ubuntu
Install Perl on Rocky Linux
Install Perl on macOS
Install Perl on FreeBSD
Perl in Docker

Search this site

Channel @aofeed Chat @aofeedchat

Contacts and cooperation:
I recommend our hosting beget.com
Write to info@aredel.com if you:
1. Want to write an article for our site or translate an article into your native language.
2. Want to place thematically relevant ads on the site.
3. Ads on my site pass maximum censorship. If you see an ad block unsuitable for school-age children, shocking or misleading - please contact us by e-mail
4. Found a mistake, inaccuracy, bug, etc. on the site. ... .......
5. Articles can be shared on social media by clicking a network icon: