我正在尝试创建我们代码库中的自定义模块的子类。我们的模块位于包含在所有文件中的目录中。所以我们开始
use Env;
use lib "$ENV{OurKey}/RootLib"; # All of our modules are here
接下来,我有我的父模块,位于 RootLib/Dir1/Parent.pm
中,其代码已经存在很长时间了,所以我宁愿不更改其中任何一个,而是拥有 child 能够按原样继承它。
package Parent;
use strict;
use warnings;
use Env;
use lib "$ENV{OurKey}/RootLib";
sub new {
my $proto = shift;
my $class = ref($proto) || $proto;
my $self = {};
# Some other stuff
bless ($self, $class);
return $self;
}
此时,我有点迷失,因为我已经看到了许多不同的方法来定义子构造函数,但没有一个对我有用。这就是我所拥有的,但它不起作用,因为在子包中找不到应该从父包继承的子例程。子包位于 RootLib/Dir1/Dir2/Child.pm
package Child;
use strict;
use warnings;
use vars qw(@ISA);
use Env;
use lib "$ENV{OurKey}/RootLib";
require Dir1::Parent;
push @ISA, 'Dir1::Parent';
sub new {
# This constructor is clearly incorrect, please help
my $proto = shift;
my $class = ref($proto) || $proto;
my $self = Parent::new($class);
bless ($self, $class);
return $self;
}
然后,在我的 test.pl 文件中,我有
use Env;
use lib "$ENV{OurKey}/RootLib";
use Dir1::Dir2::Child;
my $childObj = Child->new();
$childObj->inheritedParentSubroutine( ... ); # Cannot find this subroutine
最佳答案
父类声明它位于Parent包
中(即使包含它的文件是Dir1/Parent.pm
),因此子类的@ISA
应该只包含 Parent
。
或者您可以使用一些额外的 use lib ...
语句来解决不幸的目录结构。
package Child;
use lib "$ENV{OurKey}/RootLib/Dir1";
require Parent; # found in $OurKey/RootLib/Dir1/Parent.pm
our @ISA = ('Parent');
...
# test.pl
use lib "$ENV{OurKey}/RootLib/Dir1/Dir2";
use Child; # found in $OurKey/RootLib/Dir1/Dir2/Child.pm
...
关于perl - 正确的 Perl OO 继承,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32978483/