Broad Network


Perl Object Constructor and Destructor

Perl Object Oriented Programming – Part 2

Perl Course

Foreword: In this part of the series, I talk about Perl object constructor and destructor.

By: Chrysanthus Date Published: 26 Sep 2015

Introduction

This is part 2 of my series, Perl Object Oriented Programming. In this part of the series, I talk about Perl object constructor and destructor. A constructor is a method that you the coder define. A constructor instantiates (creates) an object of the class. The default action of the destructor is to erase the object from memory. A destructor is a method already in Perl, with an empty body. You can place certain statements of your choice, in the body. If you do not place any statements in the body, the object in memory is simply erased, and nothing else is done. You should have read the previous part of the series before coming here as, this is the continuation.

A Simple Constructor
The following code shows a simple constructor in a class description:

use strict;

    {package TheClass;

        sub new
            {
                bless {}, $_[0];
            }

        #some method definitions
    }

The name of the class is TheClass. It is conventional to start the name of the class with a capital letter (and the name of any object with a small letter). The name of the constructor method is, new(). You can choose some other name for this constructor method, but most people choose new. The constructor method is defined in the class description. The constructor will be called as follows:

    TheClass->new();

The class name is used to call the constructor method. This means the first argument to the method called, is the name of the class. That is why you have $_[0] as the second argument of the bless() function. If $_[0] is omitted, it is still assumed as the second argument to the bless() function. It is the bless() function that instantiates the object. The object is the blessed hash, meaning it is a hash whose reference can be used to call the methods of the class (description). An ordinary hash (non blessed hash) cannot be used to call the methods of the class. The bless() function returns the reference of the hash.

The hash in this case is anonymous. The result of the last statement of any Perl function (method) definition is always returned, without use of the return reserved word. So, the bless() function should be the last statement of the constructor, otherwise you use a return reserved word to return the blessed hash reference.

Note: when the hash reference is used to call any method of the class, outside the package (class description), the first argument to the method called, is the reference to the hash and not the name of the class.

Initialization
The above class description has a constructor method that does not assign any attribute/value pairs, initially to the object (hash). With the above constructor, attribute/value pairs have to be added to the hash (object) after the object has been created (instantiated). In some situations, you would want to create an object with some initial attribute/value pairs. That is initialization. Further attribute/value pairs will have to be added after instantiation.

There are two main ways of initializing the object (blessed hash) in Perl: you can either send the initialized values for the attributes as arguments in the new (constructor) method call or you hard code the attribute/value pairs in the hash in the new method definition.

The following code illustrates how to send the initialized values as arguments for the new method call:

use strict;

    {package TheClass;

        sub new
            {
                bless {aa=>$_[1], bb=>$_[2]}, $_[0];
            }

        #method definitions
    }

    my $obj = TheClass->new("one", "two");
    $obj->{cc} = "three";

    print $obj->{aa}, "\n";
    print $obj->{bb}, "\n";
    print $obj->{cc}, "\n";

The output is:

one
two
three

In the code, there are two initialized attribute/value pairs, which are aa/one and bb/two. aa is an attribute and its value is one. bb is an attribute and its value is two. The names, aa and bb have been given by you the coder (some other names could have been given). There is a third attribute/value pair, which is cc/three. This attribute/value pair has been given after instantiation, outside the class.

In the new() method definition, the bless statement assigns the first argument of new(), which is $_[1] to the attribute, aa; and also assigns the second argument of new(), which is $_[2] to the attribute, bb. All these take place in the anonymous hash. The anonymous hash returns a reference that is also returned by the bless function (statement). The bless() statement in the new method definition, blesses the anonymous hash with the name of the class, $_[0]. Remember, when a class method is called with the class name, the first argument to the method is the class name in $_[0], implicitly. The first typed argument of the method call, is then in $_[1]. For a non-class function, the first typed argument is $_[0], explicitly.

Note that the new() method definition could have been coded as follows:

        sub new
            {
                my $self = {};
                $self->{aa} = $_[1];
                $self->{bb} = $_[2];
                bless $self, $_[0];
            }

Remember, to access the element of a hash using a variable holding a reference to the hash, use the syntax:

    $href->{'key'}

The quotes can be omitted if the key name does not have any space.

The following code shows how to hard code the attribute/value pairs into the hash to be blessed:

use strict;

    {package TheClass;

        sub new
            {
                bless {aa=>"one", bb=>"two"}, $_[0];
            }

        #method definitions
    }

    my $obj = TheClass->new();
    $obj->{cc} = "three";

    print $obj->{aa}, "\n";
    print $obj->{bb}, "\n";
    print $obj->{cc}, "\n";

This program solves the same problem as the previous program. Note that the new() method call has no arguments. The new() method definition could have been written as:

        sub new
            {
                my $self = {};
                $self->{aa} = "one";
                $self->{bb} = "two";
                bless $self, $_[0];
            }

Destructor
Any Perl object (blessed hash) is automatically destroyed by Perl, when it goes out of scope. Any Perl object has a default DESTROY method, which would destroy (erase from memory) the object. However, you add statements to the DESTROY method body to do some house keeping. The following code illustrates how you can add statements to the destroy function:

use strict;

    {package TheClass;

        sub new
            {
                bless {aa=>"one", bb=>"two"}, $_[0];
            }

        sub DESTROY
         {
             my $self = shift;
             print %{$self}, " has been destroyed";
         }

        #method definitions
    }

    my $obj = TheClass->new();
    $obj->{cc} = "three";

I tried the code in my computer and the output was:

    bbtwoaaoneccthree has been destroyed

The hash is represented at the output by all its key/value pairs. Note the casing of the destroy method name. It has to be like this, all characters in uppercase. In the method definition, the shift function in the first statement removes the first argument of the @_ array and assigns to the variable, $self. This then holds the reference of the object, which is the first argument to the method. This default method has been called with the object, implicitly. The second statement dereferences the object reference and prints the string. The destroy method already exists implicitly in every class (package) with the default behavior, but with an empty body.

If you do not have anything to type into the body of the destroy method definition, then do not type the whole DESTROY function. In that case, it will still be called implicitly (unknown to you) and destroy the object.

In the above code, the destroy method has been called at the end of the file.

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

Chrys

Related Links

Perl Basics
Perl Data Types
Perl Syntax
Perl References Optimized
Handling Files and Directories in Perl
Perl Function
Perl Package
Perl Object Oriented Programming
Perl Regular Expressions
Perl Operators
Perl Core Number Basics and Testing
Commonly Used Perl Predefined Functions
Line Oriented Operator and Here-doc
Handling Strings in Perl
Using Perl Arrays
Using Perl Hashes
Perl Multi-Dimensional Array
Date and Time in Perl
Perl Scoping
Namespace in Perl
Perl Eval Function
Writing a Perl Command Line Tool
Perl Insecurities and Prevention
Sending Email with Perl
Advanced Course
Miscellaneous Features in Perl
Perl Two-Dimensional Structures
Advanced Perl Regular Expressions
Designing and Using a Perl Module
More Related Links
Perl Mailsend
PurePerl MySQL API
Perl Course - Professional and Advanced
Major in Website Design
Web Development Course
Producing a Pure Perl Library
MySQL Course

BACK NEXT

Comments

Become the Writer's Fan
Send the Writer a Message