Sunday, September 6, 2009

Perl inheritance - The basics

We can implement inheritance in Perl using packages (as our "classes").
The following sample will demonstrate package inheritance:

First, Lets create our base package, in this sample, I have created a simple logger package which has a constructor and a "print" method:

# Module Name

package mylogger;
## Constructor
sub new {
  print "mylogger  :new\n";
  my $package = shift;
  return bless({}, $package);
## Print Method
sub print
    print "mylogger  :print - " . $_[1] . "\n";

If my main application will call this module:
use mylogger;
my $myLogger = mylogger->new();
$myLogger->print("Hello world");

The Ouput will be as following:
mylogger  :new
mylogger  :print - Hello world

Lets now create a newer logger which inherit the previous one and print the message time and date:
# Module Name
package newlogger;
use mylogger;
## Inherit from mylogger
our @ISA=qw(mylogger);
sub print
    print "newlogger :print - " . $_[1] . " (at ". localtime(time) .  ")\n";

Now, If we will call the new loggers following:
my $newlogger = newlogger->new();
$newlogger->print("Hello world");

The following output will appear:
mylogger  :new
newlogger :print - Hello world (at Sun Sep  6 22:00:52 2009)

OK, What happen here?
The first module is straight-forward, Please refer to my previous entry regarding Perl modules,
The second one act as following:
When newlogger->new() is being called, Perl start looking for the "new" method in the newlogger package, Since we don't have one, Perl try to look the requested method in the packages which are listed in the @ISA list.
Since we have a "new" method in our "mylogger" package, Perl call this function and do the following:
First its print the "mylogger  :new\n"  message.
Second its return a reference (by using bless) to the inserted package, which is "newlogger".

And since the "new" function returned a "newlogger" object, When the app call the $newlogger->print method, its actually calling the new method with the time stamp.