Perl Programming/Objects

Previous: Code reuse (modules) Index Next: Structure and style



When Perl was initially developed, there was no support at all for object-orientated (OO) programming. Since Perl 5, OO has been added using the concept of Perl packages (namespaces), an operator called bless, some magic variables (@ISA, AUTOLOAD, UNIVERSAL), the -> and some strong conventions for supporting inheritance and encapsulation.

An object is created using the package keyword. All subroutines declared in that package become object or class methods.

A class instance is created by calling a constructor method that must be provided by the class, by convention this method is called new()

Let's see this constructor.

package Object;

sub new {
  return bless {}, shift;

sub setA {
  my $self = shift;
  my $a = shift;

sub getA {
  my $self = shift;
  return $self->{a};

Client code can use this class something like this.

my $o = Object->new;
print $o->getA;

This code prints 10.

Let's look at the new contructor in a little more detail:

The first thing is that when a subroutine is called using the -> notation a new argument is pre-pended to the argument list. It is a string with either the name of the package or a reference to the object (Object->new() or $o->setA. Until that makes sense you will find OO in Perl very confusing.

To use private variables in objects and have variables names check, you can use a little different approach to create objects.

package my_class;
use strict;
use warnings;
  # All code is enclosed in block context

  my %bar;  # All vars are declared as hashes
  sub new {
    my $class = shift;
    my $this = \do{ my $scalar }; # object is a reference to scalar (inside out object)
    bless $this, $class;
    return $this;

  sub set_bar {
    my $this = shift;
    $bar{$this} = shift;

  sub get_bar {
    my $this = shift;
    return $bar{$this};

Now you have good encapsulation - you cannot access object variables directly via $o->{bar}, but only using set/get methods. It's also impossible to make mistakes in object variable names, because they are not a hash-keys but normal perl variables, needed to be declared.

We use them the same way like hash-blessed objects:

my $o = my_class->new();
print $o->get_bar();

prints 10

Further reading


Previous: Code reuse (modules) Index Next: Structure and style