繼承對物體起作用。你想要做的是導入,而不是繼承。我在下面概述了一個繼承和導入的例子。
繼承:
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;
導入:
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();
需要注意的是,在未來的Perl版本(5.26。0),則@INC
默認不包含當前工作目錄,因此如果這些模塊文件位於本地目錄中,則爲use One;
或use Two;
,則必須添加use lib '.';
或unshift @INC, '.';
等。
[Perl的@INC是如何構建的? (又名什麼是影響Perl模塊搜索的方式?)](http://stackoverflow.com/questions/2526804/how-is-perls-inc-constructed-aka-what-are-all-the影響,在哪裏) – dubes
@dubes我不同意這種評估。 – simbabque