【发布时间】:2018-02-03 23:21:57
【问题描述】:
我正在尝试为我们的代码库中的自定义模块创建一个子类。我们将模块放在一个目录中,该目录包含在所有文件中。所以我们从
use Env;
use lib "$ENV{OurKey}/RootLib"; # All of our modules are here
接下来,我有我的父模块,位于RootLib/Dir1/Parent.pm,它的代码已经存在很长时间了,所以我宁愿不改变任何一个,而是让孩子能够从它继承。
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
【问题讨论】:
-
Env这样使用是一个相当危险的模块;我建议仅将它与一组有限的包含一起使用:例如,use Env qw/ $PATH /;。此外,您不需要 需要use以$ENV{OurKey}的身份访问环境变量;原始 Perl 具有这种能力。 -
use Moose;或相似者之一。 -
注:1)
use Env;没用。 2)use lib "$ENV{OurKey}/RootLib";应该只位于脚本(.pl 文件)中,而不是模块(.pm 文件)中。 -
@el.pescado,Moose 不是一个选择。这将需要比使其正常工作所需的更多更改。
use Env、@ikegami 也是如此
标签: perl oop inheritance