Perl Object Concept

Perl provides us some tools to build object oriented system. Perl object oriented concepts are based on references, anonymous arrays and hashes.

Basic Object

An object is simply a data structure, it knows the class name to which it belongs. It is stored as a reference in a scalar variable. The same scalar variable can hold different objects in different classes as it only holds a reference to the object.

A class is simply a package. It contains methods that operate on objects (create and manipulate it).

A method is a subroutine that expects an object reference or a package name as the first argument.

Class Declaration

To create a class, we need to create a package in Perl. A package contains variables and subroutines which can be reused.

As each class is a package, it has its own namespace consisting of symbol names. A class is the namespace created using package keyword. It is generally implemented in the module with the same name as class. For example, My:: File would be implemented in file File.pm and location will be directory My with following content.

Example
snippet
package My::File;
use strict;
use warnings;
1;

Here 1 at the end indicates successful loading of the file.

The scope of a package extends to the file end or until another package keyword is encountered.

Constructor

A code needs a constructor for a fully functional class.

Mostly, a constructor is implemented as the new method.

Example
snippet
sub new {
    my ($class, %args) = @_;
    return bless \%args, $class;
}

Instance/Object

An instance or object is a blessed reference mostly to hash. Blessing something means we are blessing the thing that the variable refers to.

Example
snippet
use Scalar::Util 'blessed';
  my $Ana = {};
  my $Christian = $Ana;
  bless $Ana, 'Happiness';
  print blessed( $Christian ) // 'not blessed';    # Class
  print "\n";
  $Christian = "some other value";
  print blessed( $Christian ) // 'not blessed';    # not blessed
  print "\n";
Output
Class not blessed

In the above program, when we call 'bless' on a variable, we are blessing the data structure variable is referring to. Reference is not getting blessed. And hence when we call blessed( $Christian ) second time, it returns false. Because $Christian is not storing a reference to an object.

Destructor

Perl destructor is used to clean the memory allocated to an object when it is no longer required. It is done automatically in Perl when an object goes out of scope. And so it is usually not implemented in Perl.

To implement destructor, a function is there called DESTROY. It is called just before the object is destroyed and memory is reclaimed by Perl.

Example
snippet
package MyExample;
sub DESTROY {
   my ($self) = @_;
   print "MyExample::DESTROY called\n";
}

Defining Methods

There is no special syntax to define a method in Perl. It is simply a regular subroutine which is declared with 'sub' keyword.

A method expects an object or a class name as its first argument.

To invoke a method, -> operator is used.

To call a method as an object, following syntax is used:

snippet
$object -> method

In left hand side it has the object name and on right hand side it has the method name.

On calling a method, left side object is passed onto the right side as the first argument.

Example

In this example, we'll set one helper method and one helper function to set the student's name and rank.

Step 1 In hw.pl file, Define a helper method studentName to get student's name.

Define a helper function studentRank to get student's rank.

snippet
sub studentName {
    return $self->{_name};
}
sub studentRank {
    my ( $self, $name ) = @_;
    $self->{_name} = $name if defined($name);
    return $self->{_name};
}

Step 2 In student.pm file, write Student package and helper function.

snippet
#!/usr/bin/perl 
package Student;
sub new	
{
    my $class = shift;
    my $self = {
        _name => shift,
        _rank  => shift,   
    };
    # Print all the values just for clarification.
    print "Student's name is $self->{_name}\n";
    print "Student's rank is $self->{_rank}\n";
    
    bless $self, $class;
    return $self;
}
sub studentRank {
    my ( $self, $name ) = @_;
    $self->{_name} = $name if defined($name);
    return $self->{_name};
}
sub studentName {
    my( $self ) = @_;
    return $self->{_name};
}
1;

Step 3 In person.pl file, we'll use Student object to get the output.

snippet
#!/usr/bin/perl
use Student;
$object = new Student( "Ana", "9th");
# name which is set using constructor.
$name = $object->studentName();
print "Name set using constructor is : $name\n";
# name set using helper function.
$object->studentRank( "Anastasia" );

# getting name set by helper function.
$name = $object->studentName();
print "Name set using helper is : $name\n";
Output
Student's name is Ana Student's rank is 9th Name set using constructor is : Ana Name set using helper is : Anastasia

Inheritance

Inheritance means child classes will inherit the properties and methods of the parent class. Hence to reuse a code, you can simply inherit it. In Perl @ISA array defines inheritance.

While using inheritance, following points should be considered:

  • It will search object class for the given method i.e; variable.
  • It searches class defined in object class's @ISA array.
  • If no method is found in above steps, it uses an AUTOLOAD subroutine.
  • If still method is not found, it searches with the UNIVERSAL class which is a part of standard Perl library.
  • If still not found, then runtime exception occurs.

Inheritance can also be declared using parent directive which replaces the older base directive.

Example

Our script loads a module, calls its constructor and then calls two methods.

Create hw.pl file with following script. Here, module itself declares its inheritance using parent directive.

snippet
#!/usr/bin/perl
use strict;
use warnings;
use Module1;
my $myObj = Module1->new;
$myObj->setHello;
$myObj->setBye;
Output
This is Hello message from Module1 This is Bye message from Module2

Create Module1.pm file with following script. It declares the module from where we inherit constructor and another method.

snippet
package Module1;
use strict;
use warnings;
use parent 'Module2';
sub setHello {
    print "This is Hello message from Module1\n";
}
1;

Create Module2.pm file with following script.

snippet
package Module2;
use strict;
use warnings;
sub new {
    my ($class) = @_;
    return bless {}, $class;
} 
sub setBye {
    my ($self) = @_;
    print "This is Bye message from Module2\n";
    return;
}
1;

On calling new method from Module1, Perl will not find it in Module1. It will look for it in the next module Module2 in the inheritance chain. Hence, new method will be called from Module2.

Polymorphism

Polymorphism means methods defined in the base class will override methods defined in parent class.

It appends the functionality of an existing class without reprogramming the whole class.

Example
snippet
package A;
    sub A1 {
        print("Inside A::A1\n");
    }
package B;
    @ISA = (A);
    sub A1 {
        print("Inside B::B1\n");
    }
package main;
    B->A1();
Output
Inside B::B1

The sub A1, defined in class B overrides that was inherited from class A.

Related Tutorial
Follow Us
https://www.facebook.com/Rookie-Nerd-638990322793530 https://twitter.com/RookieNerdTutor https://plus.google.com/b/117136517396468545840 #
Contents +