【发布时间】:2012-02-14 22:21:09
【问题描述】:
我有一个父包和几个子孙包:
#parent
package Mother;
sub new {
my ($class, $args) = @_;
my $self = bless {}, $class;
return $self;
}
# load sub...
sub getGrandchildren {
my ($self, $package) = @_;
# find all grandchildren dynamicly
my @grandchildren = ('Mother::Child::Grandchild');
# load all found packages and load their config
foreach my $grandchild (@grandchildren) {
# require etc
# load config
my $c = $grandchild->getConfig();
# damn ... $c is undef
# I expected { x => 2 } from grandchild
warn Dumper $c;
$config{$grandchild} = $c;
}
}
# this subroutine should be used
# by children and grandchildren
sub getConfig {
my ($self) = @_;
use no strict 'refs';
return ${$self::."config"};
}
1;
# child
package Mother::Child;
use parent qw/Mother/;
our $config = { x => 1 };
sub new {
my ($class, $args) = @_;
my $self = $class->SUPER::new($args);
$self->getGrandchildren(__FILE__);
return $self;
}
1;
# grandchild
package Mother::Child::Grandchild;
use parent qw/Mother::Child/;
our $config = { x => 2 };
sub new {
my ($class, $args) = @_;
my $self = $class->SUPER::new($args);
return $self;
}
1;
如果我这样称呼:
my $child = Mother::Child->new();
所有孙子都已加载,并且应该加载他们的配置。
我试图通过一个仅在父级中定义的子例程“getConfig()”来实现这一点。
问题是使用
加载配置$grandchild->getConfig();
返回 undef。
我想避免在每个孩子和孙子中创建一个子例程 getConfig() 来返回正确的配置(从孩子或孙子)。
这种子/孙结构可以做到这一点吗?还是我做错了什么?
解决方案
按照@bvr 的建议,我用 ${$self."::config"} 替换了 getConfig 中的返回值,并添加了“no strict 'refs'”。
【问题讨论】:
-
你想创建某种树结构,我猜?如果是这样,为什么不只拥有一个
Node类并担心每个特定节点是否有父节点、子节点等?事实上,为什么不使用(或构建)诸如 Tree 之类的 CPAN 模块? -
“节点类”是什么意思?我对 Perl 很陌生,我不知道 Tree。另一方面,我只想要一个基本的父子结构,“使用父...”就足够了。
-
如果您要对树进行建模,那么不要尝试为每一代制作单独的包(...
Mother::Child::Child类或Mother::Child::Child::Child类呢, ETC?)。只需拥有一堆节点并担心它们之间的关系。我建议您查看 Tree 或Tree::Simple。 -
哦,请确保始终、始终、始终
use strict;和use warnings;。每一个。单身的。时间。 -
谢谢。我使用警告和严格。总是:)。
标签: perl inheritance parent-child