Perl:Multiple inheritance, example

Multiple inheritance means, a child package has two or more parent packages.

To understand it with example, you need to create below 4 files.

1) fruit.pm (parent package)

.pm Files are perl’s module files.

2) guava.pm (second parent package)

3) bigfruit.pm (child package of guava and fruit)

4) core.pl (main executable file which will use only bigfruit package)

After that run the core.pl and observe the output.

———————————————————————————–

#fruit.pm

use strict;
package fruit;
sub new {
my $class = shift;
my $self = {
name => shift,
color => shift,
};
bless $self, $class;
return $self;
}
sub fruitmsg {
print “\nThis message is from fruit package.Fruits are good for health.\n”;
};
1;

———————————————————————————–

———————————————————————————–

#guava.pm

use strict;
package guava;

sub new {
my $class = shift ;
my $self = {
name => shift,
color =>shift,
size => shift,
taste => shift,
};
bless $self,$class;
return $self;
}
1;

———————————————————————————–

———————————————————————————–

#bigfruit.pm

use strict;
use guava;
use fruit;
package bigfruit ;

our @ISA=qw (guava fruit);
sub new {
my $class = shift;
my $self = $class->SUPER::new($_[0],$_[1],$_[2],$_[3]);
$self ->{size} = “big”;
bless $self, $class;
return $self;
}
1;

———————————————————————————–

———————————————————————————–

#core.pl

use strict;
use bigfruit;

my $mango= new fruit(“mango”,”yellow”,”small”,”sweet”);

print $mango->{name} ;
print “\t”,$mango->{color} ;
print “\t”,$mango->{size} ;
print “\t”,$mango->{taste} ;

my $mango= new guava(“mango”,”yellow”,”small”,”sweet”);

print “\n”,$mango->{name} ;
print “\t”,$mango->{color} ;
print “\t”,$mango->{size} ;
print “\t”,$mango->{taste} ;

my $f2 = new guava(“guava”,”green”,”small”,”good”);
print “\n”,$f2->{name};
print “\t”,$f2->{color};
print “\t”,$f2->{size};
print “\t”,$f2->{taste};

my $f3 = new bigfruit(“melon”,”green”,”new”,”water”);
print “\n”,$f3->{name};
print “\t”,$f3->{color};
print “\t”,$f3->{size};
print “\t”,$f3->{taste};

&fruit::fruitmsg();
———————————————————————————–

Advertisements

Tags: , ,

One Response to “Perl:Multiple inheritance, example”

  1. koolkedar Says:

    Output of the above script is:

    mango yellow
    mango yellow small sweet
    guava green small good
    melon green big water
    This message is from fruit package.Fruits are good for health.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s


%d bloggers like this: