Broad Network


Constructor and Destructor for Perl Objects

Object Oriented Programming in Perl - Part 2

Forward: In this part of the series, we look at the Constructor and Destructor for Perl Instantiated Objects.

By: Chrysanthus Date Published: 2 Mar 2013

Introduction

This is part 2 of my series, Object Oriented Programming in Perl. You should have read the previous part of the series before reaching here. In this part of the series, we look at the Constructor and Destructor for Perl Instantiated Objects.

Note: If you cannot see the code or if you think anything is missing (broken link, image absent), just contact me at forchatrans@yahoo.com. That is, contact me for the slightest problem you have about what you are reading.

A Constructor
A constructor is a constructor function (constructor method). This was introduced in the previous part of the series. A constructor is a function in a class that the class uses to instantiate (create) an object having its properties and methods. The following class description shows a constructor function with the minimum number of statements.

    {package Calculator;

        my $self = {};

        sub new
            {
                my $class = $_[0];
                bless $self, $class;
            }

        sub add
            {
                my $sum = $self->{'num1'} + $self->{'num2'};
                return $sum;
            }

    }

The constructor method has the name, new. As a minimum, the constructor function should have at least two statements like the one above. When the constructor method is called, the first statement assigns the package name to a variable ($class), which is the implicit first argument (you do not code this) sent by the constructor function call. Note: a package is a class. The second statement blesses a reference. This reference points to a memory region that holds the instantiated object of the class. In order to do this, the bless operator needs the package name (from $class above) and an already created reference of a hash.

Arguments for the Constructor Function
The constructor function can have arguments. Here, the first argument during the constructor function call is implicit and is still the class (package) name. In the called constructor function inside the class, the arguments to use from @_, for ordinary purposes, are the $_[1], $_[2], $_[3], etc., since $_[0] has but the class name. The following code shows how to handle arguments in a constructor function:

use strict;

print "Content-Type: text/html\n\n";

print "<html>\n";
print "<head>\n";
print "<title>Code Sample</title>\n";
print "</head>\n";
print "<body>\n";


    {package TheClass;

        my $self = {};

        sub new
            {
                my $class = $_[0];

                print $_[1] . "<br />";
                print $_[2] . "<br />";

                bless $self, $class;
            }

    }

    my $anObj = TheClass->new("one","two");


print "</body>\n";
print "</html>\n";

Note: the first implicit argument of other methods of an instantiated object (not the class) is the reference to the instantiated object.

The above constructor has simply printed out the arguments, received. A typical constructor initializes the properties of the instantiated object –see below.

Constructor and Initialization
Initialization in a typical Perl constructor is simply to give key/value pairs to the hash. Remember the key/value pairs are the properties of the object. Read and try the following program that illustrates this:

use strict;

print "Content-Type: text/html\n\n";

print "<html>\n";
print "<head>\n";
print "<title>Code Sample</title>\n";
print "</head>\n";
print "<body>\n";


    {package Calculator;

        my $self = {};

        sub new
            {
                my $class = $_[0];

                $self->{'num1'} = $_[1];
                $self->{'num2'} = $_[2];

                bless $self, $class;

            }

        sub add
            {
                my $sum = $self->{'num1'} + $self->{'num2'};
                return $sum;
            }

        sub subtract
            {
                my $difference = $self->{'num2'} - $self->{'num1'};
                return $difference;
            }

    }


    my $obj = Calculator->new();
    $obj->{'num1'} = 2;
    $obj->{'num2'} = 3;

    my $result1 = $obj->add();
    my $result2 = $obj->subtract();
    print $result1 . "<br>";
    print $result2 . "<br>";


print "</body>\n";
print "</html>\n";

There are two properties, num1 and num2. They are initialized by $_[1] and $_[2] of the @_ array sent by the constructor call. Remember, when dealing with the class, the first value of this array is the class name. There are two methods: one adds the values of the properties and the other subtracts the value of the first property from the value of the second.

Each time the class code is called to instantiate an object, a new hash with its new reference is created. In the above code, the creation of the hash is done before the constructor is executed.

The secret of Perl OOP is to have the bless statement as the last statement in the constructor method. The result of any last statement in a Perl function (method) is returned without the “return” instruction. The bless statement turns the hash into an object and relates it to the class description code. The initialization (assignment) statements should come before the bless statement, in the constructor method.

Destructor
When an object goes out of scope, it is automatically destroyed, by the Perl system.

That is it for this part of the series. We stop here and continue in the next part.

Chrys

Related Links

Perl Reference
Object Oriented Programming in Perl
Date and Time in Perl
Regular Expressions in Perl
Perl Course
Web Development Course
Major in Website Design

BACK NEXT

Comments

Become the Writer's Fan
Send the Writer a Message