在基类Base.pm
中:
package Base;
use Modern::Perl;
sub new {
return bless {}, shift;
}
sub hi {
say 'hi from base class';
}
1;
在派生类Derived.pm
中:
package Derived;
use parent Base;
sub hi {
say 'hi from derived class';
}
1;
在main.pl
:
#!/usr/bin/env perl
use Derived;
my $d = Derived->new;
$d->hi;
运行main.pl
:
String found where operator expected at Derived.pm line 5, near "say 'hi from derived class'"
(Do you need to predeclare say?)
syntax error at Derived.pm line 5, near "say 'hi from derived class'"
Compilation failed in require at ./main.pl line 3.
BEGIN failed--compilation aborted at ./main.pl line 3.
似乎Modern::Perl
似乎没有被派生类导入。
可以在派生类中明确use Modern::Perl
来解决,但我希望减少这样的样板代码。
如何使派生类使用基类模块?
答案 0 :(得分:1)
除了面向对象模块的基类之外,您必须在任何需要的地方使用模块。
如果use Base
包含基本类所使用的所有,无论是否必要或适当,都会有不必要的尴尬。
答案 1 :(得分:1)
如果您希望导入所有类的样板use
语句(编译指示,导入等),我会查看类似Syntax::Collector的内容来处理它。
<强> MyApp的/ Syntax.pm 强>
package MyApp::Syntax;
use Syntax::Collector -collect => q{
use Modern::Perl 2013;
use List::Util 1.35 qw( first any all reduce );
use Scalar::Util 1.35 qw( blessed weaken );
};
1;
<强> MyApp的/ Base.pm 强>
package MyApp::Base;
use MyApp::Syntax;
...;
1;
<强> MyApp的/ Derived.pm 强>
package MyApp::Derived;
use MyApp::Syntax;
use parent "MyApp::Base";
...;
1;
答案 2 :(得分:0)