Perl - Object Orientation Basics
In a Nutshell - CIW Course Section 2, Part B3, Chapter 3
Objects Overview
An object, in Perl terms, is a method of encapsulating data and methods into a single entity. I felt that the course notes used object orientation terminology a little too liberally, making the subject appear more complicated than it really is.
When broken down into simpler terms the ideas behind object orientation become easier to understand.
Object Constructor
The constructor is simply a function that creates an instance of the object. It, generally, assigns values to hash elements which become the properties of the object. This function does not create an object until such time as it is called and assigned to a variable, at which time the variable represents the object.
#!c:\perl\bin\perl.exe
package Car;
1;
sub new
{
my $object = {};
$object->{"make"} = $_[1];
$object->{"model"} = $_[2];
$object->{"style"} = $_[3];
$object->{"engine capacity"} = $_[4];
$object->{"year"} = $-[5];
return bless $object;
}
The new function provides the means for creating an object with five properties. The bless keyword is important, as it is this, that promotes the item to object status allowing it to possess properties and methods.
#!c:\perl\bin\perl.exe
require Car;
$mycar = new Car("Audi", "A4 Avante", "Estate", "1800",
"1999");
$mywifescar = new Car("Ford", "Focus Ghia", "Hatchback", "2000",
"2002");
print $mycar->{"model"}, "\n";
print $mywifescar->{"model"}, "\n";
We can now write a script to utilise our new constructor and create object instances. To do this we call the new method of package Car passing five parameters which will become the object properties.
Inheritance
Inheritance allows a new class to be created which will extend the functionality of an existing object class.

