You are on page 1of 6

Objects, Methods, Class

Object
Within Perl, an object is merely a reference to a data type that
knows what class it belongs to. The object is stored as a
reference in a scalar variable. Because a scalar only contains a
reference to the object, the same scalar can hold different
objects in different classes.
When a particular operation is performed on an object, the
corresponding method is called, as defined within the class.
A class within Perl is a package that contains the corresponding
methods required to create and manipulate objects.
A method within Perl is a subroutine, defined with the package.
The first argument to the method is an object reference or a
package name, depending on whether the method affects the
current object or the class.

Creating and Using Objects


When creating an object, you need to supply a
constructor. This is a subroutine within a package
that returns an object reference.
The object reference is created by blessing a
reference to the packages class.
For example:
package Vegetable;
sub new
{
my $object = {};
return bless $object;
}

The new method returns a reference to a


hash, defined in $object, which has been
blessed using the bless function into an object
reference.
You can now create a new Vegetable object by
using this code:
$carrot = new Vegetable;

Initialize an object
If you want to initialize the object with some information
before it is returned, you
can put that into the subroutine itself (the following example
takes the data from the supplied arguments),
sub new
{
my $object = {@_};
return bless $object;
}

which can now populate when you create a new object:


$carrot = new Vegetable('Color' => 'Orange', 'Shape' => 'Carrot-like');

To call your own initialization routine on a


newly blessed object:
sub new
{
my $object = {};
bless $object;
$object->_define();
return $object;
}

The use of a leading underscore on the method _define


is a convention used to indicate a private rather than
public method. The leading underscore convention is
not enforced, however; if someone wants to use the
method, they can call it directly if they want to.

You might also like