Monday, December 15, 2008

Understanding class inheritance in Perl

By using the global variable @ISA you could extend classes in Perl. Like C++, Perl supports single and multiple class inheritance. 

In this sample, class B derives from base class A.

#!/usr/bin/perl
use strict;
package A;

sub new {
  my $class = shift;
  my %args = @_;

  my $this = {
    M1 => $args{"P1"},
    M2 => $args{"P2"}
    };

    return bless ($this, $class);
}

package B;
our @ISA = "A";

sub new {
  my $class = shift;
  my %args = @_;

  my $this = $class->SUPER::new(@_);

  $this->{"M3"} = $args{"P3"};

  return(bless($this, $class));
}

my $a = new B(P1 => "bbb", P2 => "blue", P3 => "jjj");

print($a->{'M1'} . "\n");
print($a->{'M2'} . "\n");
print($a->{'M3'} . "\n");