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.

Attributes

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 the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.