Perl Programming/Objects

Objects
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 -&gt; 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.

Client code can use this class something like this.

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 <tt>-></tt> 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 (<tt>Object->new</tt> or <tt>$o->setA</tt>. 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.

Now you have good encapsulation - you cannot access object variables directly via <tt>$o->{bar}</tt>, 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:

prints <tt>10</tt>