s.patra s.patra - 9 months ago 44
Perl Question

multi-level inheritance in Perl

I have a question related to multi-level inheritance in Perl.

Here is my code


package first;

sub disp {
print "INSIDE FIRST\n";

package second;
@ISA = qw(first);

sub disp {
print "INSIDE SECOND\n";

package third;
@ISA = qw(second);

sub new {
$class = shift;
$ref = {};
bless $ref, $class;
return $ref;

sub show {
$self = shift;
print "INSIDE THIRD\n";



use mod;

$obj = third->new();

I have a .pm file which contains three classes. I want to access the
method in the first class using an object of third class. I'm not sure how that could work.

I tried to access using two ways:

  1. using class name => first::disp()

  2. using SUPER inside second package disp method => $self->SUPER::disp();

But am not sure how it will be accessed directly using the object of third class.

Answer Source

If you need to do that, then you have defined your classes wrongly.

The third class inherits from the second class. second has it's own definition of disp, so it never tries to inherit that method from its superclass first. That means third gets the implementation defined in second

The simple answer would be to call first::disp something else. That way second won't have a definition of the method and inheritance will be invoked again

If you explain the underlying problem, and why you want to ignore an inherited method, then perhaps we can help you find a better way

Please also note that packages and module files should start with a capital letter, and each class is ordinarily in a file of its own, so you would usually use package First in First.pm etc.