Broad Network


OOP Basics in Perl

Object Oriented Programming in Perl - Part 1

Forward: In this part of the series, we look at Perl OOP basics.

By: Chrysanthus Date Published: 2 Mar 2013

Introduction

This is part 1 of my series, Object Oriented Programming in Perl. OOP stands for Object Oriented Programming. In this part of the series, we look at Perl OOP basics.

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.

Prerequisite
There are other articles (tutorials) I have written in this blog on Perl. You need to have read them or similar articles, before reading this series. The titles of the articles in this blog, which are prerequisite to reading this series are:

- Getting Started with HTML 5
- Getting Started with ActivePerl
- Perl References

A computer language builds up. There are certain things you have to learn first and then use them to learn higher things. Each of the above titles is either a tutorial or the first tutorial in a series. If it is the first part of a series, then you should have read the whole series. If it is a tutorial standing alone, then you should have read the one part tutorial. To reach any of the articles, just type the title of the article and my name Chrys in the Search Box of this page and click Search.

I use ActivePerl and a personal web server for the code samples in this series.

Preamble
When you have a set of variables and functions (subroutines) that work together and would appear in many parts of your code, you can put all that in one generalized unit, called a class. There will be no need for repeat typing of the set. In this tutorial, we are talking about a set of variables and functions. The set of variables and functions form a class, if brought together in a special way. The functions work with the values of the variables. Under that condition, it is possible that the values of the variables and the results of the accompanying functions can be changing. In order to use the class after it has been defined, you have to create a corresponding unit from the class, everything being equal. That particular unit created is called an object. In this part of the series, I give you the basic explanation of Perl classes and their objects.

You should read this series in the order given; that is, you begin with part 1, then part 2, and so on.

Group of Variables and Functions
Let us consider a group of variables and functions that would work as a generalized unit. Read and try the following code and note that it returns the sum of 2 and 3.

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";


    my $num1 = 2;
    my $num2 = 3;

    sub add
        {
            my $sum = $_[0] + $_[1];
            return $sum;
        }

    my $result = add($num1, $num2);

    print $result;


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

You have two variables (num1 and num2) and a function (add). In the code, the function is called, and the returned sum is held in the new variable, result. The result is sent to the output (web browser).

Now the above code sums two particular numbers, which are 2 and 3. You would want a piece of code that sums any two numbers, not just 2 and 3. One possibility is to include another function that would receive the two numbers, change the values of the two variables, then call the add($no1, $no2) function. There is another possibility, which has become very popular over the years; it is to create a class, then create an object from the class that would add two particular numbers.  A class is a generalized unit of code, from which things call objects can be created to do particular tasks. An object is called the Instance of the class. Note: in the above code the two variables ($num1 and $num2) and the function (add()), work together. That is why it is advisable to have the two variables and the function in one unit called a class.

Class
A class is a generalized unit (definition) from which objects can be instantiated (created). A class is basically a code unit that has variables and functions that work together. The variables are called Properties or Member Variables and the functions are called Methods. A class can solve a problem (carry out a task), but it is generally not advisable for a class to solve a problem. It is an object created from the class that is expected to carry out a task (solve a problem), not the class.

When you create an object from a class, we say you are instantiating the class. A variable of the class is called a property or member variable of the class. A function of the class is called a method of the class. An object created from a class has the same properties and methods as the class.

A Class and Object created from the above Code
The above code can be converted into a class and object as follows:

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];
                bless $self, $class;
            }

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

    }


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

    my $result = $obj->add();
    print $result;


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

You define a class beginning with the reserved word, package, at the beginning, inside a pair of curly brackets. Then you have a space and then follow it with the name of the class. You choose whatever name you want for the class. I have given the name Calculator because the class is doing some calculation. There are statements and blocks inside the curly brackets. All the statements for the class go inside the braces. It is conventional to type the variables, which are the properties, first before the functions. Note that these variables and their assigned values should be in a hash. The variables in the class are called properties and the functions in the class are called methods. The variables and the function we had in the previous program are the same variables and function we now have in the class, typed in, from a different perspective.

In the above code the hash is empty. It will be given its key/value pairs (properties) later. These key/value pairs are the variables and their assigned values. The hash is typed in the package (class description) in a particular form (braces) so that it returns a reference. In Perl, you need a reference in order to create (instantiate) an object from a class. That is why the hash has been defined in that form. The reference is held in the variable, $self. You can choose whatever name you want for this reference holding variable, but $self is very appropriate.

You have a function (subroutine) called, new, in the class (description). This function has a special purpose. It must always be in the class description (definition). It is called the constructor method. You can give it whatever name you want, but, new, is very appropriate. The minimum you should have in the constructor function is what I have given above.

Remember, in Perl, when a function (method) is called, it receives its arguments in the @_ array, which is available implicitly as soon as the function begins execution. The first line in the constructor (method) assigns the first value of the @_ array, which is from $_[0] to the variable, $class. You can give this variable whatever name you want, but “class” is most appropriate. Whenever any method (including the constructor method) in a class is called, on behalf of the class, the first argument received is the class name; in our case this name is, Calculator. The class name is also the package name. Note that this name is sent indirectly by the calling function. It comes because we are dealing with a class (package). We are talking here about functions inside a class (package) and not functions outside a class. A function outside a class has as its first argument, the first argument actually sent.

The purpose of the function constructor, new, is to instantiate (create) an object from the class. It needs as a minimum what I have given above. In order to instantiate an object, a reference to the hash is needed. The reference the class uses is held by $self (from a hash). The second statement above in the function constructor uses the Perl operator, bless. This operator makes the hash the object and relates it to the class description. The arguments (operands) to the bless operator are the hash reference and the class name. The bless operator returns the reference held by $self. And so the constructor function returns this same reference.

The last statement of a Perl function (method or subroutine) returns its result, whether it has the return instruction or not. The last statement of the constructor method should be the bless statement.

Next, in the class description you have the definition of the method, add(). The first statement in this function (method) adds the value of the key, num2 to the value of the key, num1. These keys are of the hash whose reference is held by $self. These key/value pairs are inserted in the object. Note the use of $self, num1 and num2 in the statement. The add() method returns the sum.

After the class description above, you have the following statement that instantiates the object.

    my $obj = Calculator->new();

This statement is outside the class description. The expression on the right of the assignment operator has the class name, Calculator. This is followed by the arrow operator (->); and then the constructor method, new(). Here this method does not take any argument. However, since it is preceded by the class name, the first argument that the called function will receive is the class name (Calculator). The expression on the right of the assignment operator returns a reference. This reference is the reference held by $self, returned by the bless operator, which is, in this case, now, returned by the function constructor, new(). In Perl, you can omit the parentheses of a function call that does not have arguments. So instead of, new(), you can have, new.

The next two statements in the code are:

    $obj->{'num1'} = 2;
    $obj->{'num2'} = 3;

The object is now a region in memory, pointed to by $obj. The class is different. The class is code surrounded by curly brackets, where the first word in the braces is the reserved word, package. When an object is instantiated (created), it has the properties and methods of the class. These two statements give values to new keys of the hash in the object, and not in the class.

The next statement calls the add method of the object, which adds the values of the keys of the hash in the object. Note how the add method has been called, using the object, $obj and the arrow operator. This method does not take arguments; in other words, this method does not have typed arguments. The method returns the result of the addition. The last statement relating to the class and object, sends the result (sum) to the browser.

Remember, the key/value pairs are the properties of the instantiated object. Different instantiated objects have the same keys but different values. In the above situation, the class description has no key/value pairs; in this case, you can say it has would-be key/value pairs; key/value pairs of which will actually be seen in objects.

Object Methods with Arguments
The add() method above does not have typed arguments. Nothing stops you from having typed arguments in your method. In this case the calling method (function) should use the arguments. Now, this is what you must know about the arguments of object methods: For any method of an object, e.g. obj above, the first argument received by the called method is the reference to the object (e.g. obj) and it is not typed as an argument in the calling method (function). The following code illustrates this and in the code the reference to the instantiated object is first printed out. Read and try the code:

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];
                bless $self, $class;
            }

        sub mthd
            {
                print $_[0]."<br />";
                print $_[1]."<br />";
                print $_[2];
            }

    }


    my $obj = Calculator->new();
    $obj->mthd("one", "two");


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

For the printed object reference you will see something like,

    Calculator=HASH(0x229124)

Note: for the constructor method (new), the implicit first argument is the name of the class and not the reference to the instantiated object. At the time of the constructor function call, no object had been instantiated. On the other hand the implicit first argument of an object method is the reference to the object and not the name of the class.

Properties after Instantiation
In Perl OOP the properties (key/value pairs) can be given after instantiation of the object, as in the code segment above:

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

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

NEXT

Comments

Become the Writer's Fan
Send the Writer a Message