Yugandhar Reddy Akkisetty Yugandhar Reddy Akkisetty - 2 months ago 6
Perl Question

Inheritance in perl is showing a error in my case

I have two perl modules onee.pm and two.pm and one perl script.Following is one.pm

package one;
sub foo
{
print "this is one\n";
}
sub goo
{
print "This is two\n";
}
1;


two.pm

package two;
use one;
@ISA=(one);
sub hoo
{
print "this is three \n";
}
1;


inherit.pl

use two;
foo();


when i execute inherit.pl am getting following error.

Undefined subroutine &main::foo called at inherit.pl line 2.

Answer

Inheritance works on objects. What you're trying to do is importing, not inherit. I've outlined both an example of inheritance and importing below.

Inheritance:

One.pm:

package One;

sub foo {
    print "this is one\n";
}
1;

Two.pm:

package Two;

# Note the use of 'use base ...;'. That means that we'll inherit 
# all methods from the class we're calling it on. We can override
# any inherited methods by re-defining them if we need/want

use base 'One';

sub new {
    return bless {}, shift;
}
1;

inherit.pl:

use warnings;
use strict;

use Two;

my $obj = Two->new;
$obj->foo();

Importing:

One.pm:

package One;

use Exporter qw(import);
our @EXPORT_OK = qw(foo); # allow user to import the 'foo' function if desired

sub foo {
    print "this is one\n";
}
1;

Two.pm:

package Two;
use One qw(foo); # import foo() from One

use Exporter qw(import);
our @EXPORT_OK = qw(foo); # re-export it so users of Two can import it

1;

import.pl:

use warnings;
use strict;

use Two qw(foo);

foo();

Note that in the next Perl Release (5.26.0), @INC will not include the current working directory by default, so to use One; or use Two; if those module files are in the local directory, you'll have to add use lib '.'; or unshift @INC, '.'; or the like.

Comments