Close
Close

Classes and Objects in Perl


You have stepped into the second part of Perl - The object-oriented programming (OOP).

To understand class, take an example.

You are a student
You have a roll number

Your friend is also a student
He also has a roll number and a name.

In the programming world, it's like student is a class having attributes of name and roll number and you and your friends are objects of the student class. This means that you both will have a name and a roll number.

classes and objects in Perl

Here is another example. Think of a book having a serial number and some number of pages. Now, your science book is a book as is your computer book. Suppose the serial number of the Science book is SC12 and that of the computer book is CS34 and the number of pages are 200 and 250 respectively. It is like in the following picture:

object and class in Perl

So, here book is a class having attributes 'Page' and 'Serial number' and 'Science' and 'Computer' are objects(instances) of it.

So, now you understand that class is something which acts like a base having some definitions and objects are instances of the class following those definitions.

Hopefully, you must have got the feel of classes and objects.

You will learn OOP(Object-Oriented Programming) with Perl's default object system in this and the next chapter. There are also some other object systems available to make our object-oriented programming easier. You will learn Moose (one of those systems) later in this course. Moose is available from the CPAN and is not a part of the core language.

A Perl class is simply a package having a constructor (a special kind of function) to create objects of it and a Perl object can be any variable but mostly a reference to a hash or an array is used.

Constructor


A constructor is a function which uses bless function inside it and also returns a reference to something that has the class name associated with it (basically an object). It means that constructor is a special kind of function which has two specialties:

  1. It uses bless function
  2. It returns a reference to something that has the class name associated with it

bless


bless function is used to attach an object with a class. Its syntaxes are bless REF,CLASSNAME and bless REF. It means that REF is now an object in CLASSNAME. In the second syntax, where CLASSNAME is not given, the current package (in which it is called) is used.

So, a class is also a package but having constructor which will make and return objects of the class. Let's see an example:

use strict;
use warnings;

package Student;

#constructor
sub new{

  #the package name 'Student' is in the default array @_
  #shift will take package name 'student' and assign it to variable 'class'
  my $class = shift;

  #object
  my $self = {
    'name' => shift,
    'roll_number' => shift
  };

  #blessing self to be object in class
  bless $self, $class;

  #returning object from constructor
  return $self;
}

1;

To make an object of class 'Student', we have to write:
$obj = new Student("NAME","ROLL_NUMBER");
This will pass NAME and ROLL_NUMBER as arguments of the constructor 'new'.

When we call a constructor ('new' in our case), the name of the package ('Student' in our case) exists in the default array @_. That's why we extracted and stored it in a local variable 'class' by using my $class = shift;.

After this, we created a reference to a hash which has 'name' and 'roll_number' as its keys. Here we are creating our object. It means that our objects of the 'Student' class will be a reference to a hash and they will have 'name' and 'roll_number' as their keys.

bless $self, $class; - We have attached our object 'self' with our class 'class' ( class 'Student' is stored in variable 'class' ).

return $self; - We returned the created object from the constructor 'new'.

We can create a class in one module and use it in other Perl scripts but here (in the example) we are doing both in the same file to show it working.

use strict;
use warnings;

package Student;

#constructor
sub new{

  #the package name 'Student' is in the default array @_
  #shift will take package name 'student' and assign it to variable 'class'
  my $class = shift;

  #object
  my $self = {
    'name' => shift,
    'roll_number' => shift
  };

  #blessing self to be object in class
  bless $self, $class;

  #returning object from constructor
  return $self;
}

my $obj = new Student("Sam",01);
print "$obj->{'name'}\n";
Output
Sam

my $obj = new Student("Sam",01); - We just created an object of our class by using the constructor 'new'. As the object is a reference to a hash, so print "$obj->{'name'}\n"; printed the value associated with the key 'name'.

Methods


Methods are functions or subroutines defined in a class. Let there be a 'Square' class and a method 'get_perimeter' defined in the class to return the perimeter of the square. So, we can make different objects of the 'Square' class and by the method 'get_perimeter', we can get their perimeters.

Let's see an example of doing this:

#This is Square.pm

use strict;
use warnings;

package Square;

sub new{

  my $class = shift;

  my $self = {
    'side' =>shift
  };

  bless $self, $class;

  return $self;
}

#method in class
sub getPerimeter{
  my $self = shift;
  return 4*$self->{'side'};
}

sub getArea{
  my $self = shift;
  return $self->{'side'}*$self->{'side'};
}

1;
#File is Square.pl
use strict;
use warnings;

use Square;

my $obj = new Square(10);
print $obj->getPerimeter(),"\n";
print $obj->getArea(),"\n";
Output
40
100

Here, getPerimeter and getArea are methods inside the Square class which are returning perimeter and area of the square respectively.

isa and can


isa() and can are two useful methods which can be very useful in a program.
isa() is used to check if an object is object of a class or not. We use it on an object and pass the name of the class as its argument.
can() is used to check if an object or class has a particular method or not. It returns a reference to the sub if the method is present. If the method is not present, then it returns undef.
An example is given below using 'Square' package defined in the previous example to show their syntax:

#File is Square.pl
use strict;
use warnings;

use Square;

my $obj = new Square(10);
print $obj->isa('Square'),"\n";
print $obj->can('getArea'),"\n";
Output
1
CODE(0x9a9e98)

Creating default attribute


It is possible to pass less number of arguments than the required one while creating an object. We handle this kind of situation by using || operator. This will let you pass a default value if no value is returned from the array '@a'. For example, 'side' => shift || 1 will make side 1 if shift doesn't give any value. Let's see an example to understand its use.

#This is Square.pm

use strict;
use warnings;

package Square;

sub new{

  my $class = shift;

  my $self = {
    'side' =>shift || 1
  };

  bless $self, $class;

  return $self;
}

#method in class
sub getPerimeter{
  my $self = shift;
  return 4*$self->{'side'};
}

sub getArea{
  my $self = shift;
  return $self->{'side'}*$self->{'side'};
}

1;
#File is Square.pl
use strict;
use warnings;

use Square;

my $obj = new Square();
print $obj->getPerimeter(),"\n";
print $obj->getArea(),"\n";
Output
40
100

We didn't pass anything while making an object of the class 'Square', so 'side' became 1 because we have used 'side' =>shift || 1 in our code.

Destructors


Perl automatically destroys or frees the memory allocated to an object when a script is about to exit. But we can also do it manually using a special method called DESTROY. The DESTROY() method is called just before an object is released. Its syntax is:

sub DESTROY{
  Statement(s);
}

#This is Square.pm

use strict;
use warnings;

package Square;

sub new{

  my $class = shift;

  my $self = {
    'side' =>shift || 1
  };

  bless $self, $class;

  return $self;
}

sub DESTROY {
    my $self = shift;
    print "DESTROYED\n";
}

#method in class
sub getPerimeter{
  my $self = shift;
  return 4*$self->{'side'};
}

sub getArea{
  my $self = shift;
  return $self->{'side'}*$self->{'side'};
}

1;

Ask Yours
Post Yours
Doubt? Ask question