← Back to Perl Course | Chapter 7: Object-Oriented Perl | Lesson 2 of 7

Classes and bless

A class is just a package, and bless turns an ordinary reference into an object of that class.

In this page:

  1. Classes and bless

Classes and bless

bless takes a reference and a class name and marks the reference as belonging to that package. By convention a subroutine named new is the constructor: it creates a hash reference holding the object's data, blesses it and returns it. Calling Class->new(...) passes the class name as the first argument.

Note: Pass the class name you received to bless, as in bless($self, $class), instead of hard-coding it, so subclasses work.

Example: Classes and bless

perl
use strict;
use warnings;

package Dog;

sub new {
    my ($class, %args) = @_;
    my $self = {
        name  => $args{name}  || "Unnamed",
        sound => $args{sound} || "Woof",
    };
    return bless $self, $class;
}

package main;

my $dog = Dog->new(name => "Rex");
print "object class: ", ref($dog), "\n";
print "name stored: $dog->{name}\n";
print "sound stored: $dog->{sound}\n";
my $stray = Dog->new;
print "default name: $stray->{name}\n";

# Output:
# object class: Dog
# name stored: Rex
# sound stored: Woof
# default name: Unnamed
Common Mistakes
  1. Forgetting to return the blessed reference from new
  2. Hard-coding the class name in bless
  3. Blessing a copy of the data instead of the reference you return
Chapter Summary
  • A class is a package
  • bless ties a reference to a package
  • new is the conventional constructor
  • Objects are usually blessed hash references
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.