Reputation: 1
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.
Upvotes: 0
Views: 111
Reputation: 9296
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 functions from the package 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.
Upvotes: 4
Reputation: 54323
The inheritance has nothing to do with it. You are not exporting anything, so the foo
subroutine is not in your script's namespace.
In fact you are also mixing up object oriented concepts (the inheritance) and classic Perl modules. If you have a non oop module, you can have exporter and bring subs into your script. If you have a class, you can inherit from another class. But then you would typically not export anything.
Now if you wanted to use two
to import something from one
, essentially building something like a collection of common functions, you would need to use Exporter in one
, then use one
in two
, and then use Exporter in two
to export the functions imported from one
.
Sounds complicated? It does because it is complicated. There is no real benefit from doing that unless saving one line of use one
in your script.
Upvotes: 3