Perl's approach to object oriented programming is evolutionary, rather than revolutionary. It makes use of existing keywords and paradigms to implement a simplistic form of object oriented programming, which, nevertheless, provides a usefull addition to the already large range of programming possibilities in the language.
Perl object orientation can be confusing if you fail to understand that it is a subversion of the normal Perl paradigm. When you build classes and derive objects in Perl, you are simply working with the existing technology of the language.
When working with object orientation, Perl regards the 'package' keyword as the introduction to a class. What “package” actually does is to introduce a new namespace, a region defining the lexical scope of variables and sub-routines.
Consider this example:
package Car;
sub Doors
{
...do something
}
1; # <------- a package must always return "true"
From outside of the Car package, Doors() is invisible, until we refer to it as Car::Doors(). Now the sub-routine is visible. Those who've already met object orientation will understand that Doors() can be, correctly, described as a method of the class Car.
Although you can, legitimately, call doors as shown above with Car::Doors(), it's far more common to create a reference to the class and use Perl's reference notation to access objects. This allows us to do something along the lines of…
$Zephyr->Doors("Convertible");
Where $Zephyr is a reference to a Car object.
So, where did the reference ($Zephyr, above)) come from?
The convention is that you supply a constructor method, which is used to return a reference to a new instance of the class (package). Note that, in Perl, there's always more than one way to do anything; this way of doing things, though, works well for most people's requirements.
package Car;
sub New
{
my $class = shift;
my $self = {};
bless $self, $class;
return $self;
}
sub Doors
{
my ($self, @args) = @_;
my $model = $args[1];
if( $model eq "Convertible" ) { print "2\n"; } else { print "4\n";}
}
1; # <------- a package must always return "true"
The New() sub-routine is the constructor. You may call a constructor by any name that takes your fancy but most people prefer “new” because it's so descriptive of what it does.
The key to the whole process is the bless command. This does nothing more than associate the string in the second argument to the pointer in the first argument, effectively creating the object:
$Zephyr = Car->New();
$Zephyr->Doors("Convertible");
…which will print the number “2”.
In the examples above, you may have noticed that the sub-routines appear to be finding a parameter ($self) from nowhere. What's actually happening is that the arrow notation is creating the first parameter automatically. Whenever Perl finds an arrow reference to a class name, which it infers if the value on the left of an arrow is a package name, it pushes that name into @_ as the first argument.