Objects in Perl

Let us define a few preliminary terms before we start implementing objects in Perl.

An object (also called an instance), like a given car, has the following:

  • Attributes or properties (color: red; seating capacity: 4; power: 180 HP)

  • Identity (my car is different from your car)

  • Behavior (it can be steered and moved forward and backward)

Objects of a certain type are said to belong to a class. My car and your car belong to the class called Car or, if you are not too worried about specific details, to a class called Vehicle. All objects of a class have the same functionality.

In this section, we study how to create objects and how to enrich basic designs using inheritance and polymorphism.


An object is a collection of attributes. An array or a hash can be used to represents this set, as we discussed in Chapter 2. For example, if you need to keep track of an employee’s particulars, you might choose one of these approaches:

# Use a hash table to store Employee attributes
%employee = ("name"     => "John Doe",
             "age"      => 32,
             "position" => "Software Engineer");
print "Name: ", $employee{name};

# Or use an array
$name_field = 0; $age_field = 1; $position_field = 2;
@employee = ("John Doe", 32, "Software Engineer");
print "Name: ", $employee[$name_field];

The section Section 8.1 in Chapter 8 describes a more efficient approach for storing attributes. Meanwhile, we will use a hash table for all our examples.

Unique Identity

Clearly, one %employee won’t suffice. Each employee ...

Get Advanced Perl Programming now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.