【发布时间】:2016-09-07 13:22:16
【问题描述】:
我在以下属性初始化顺序方面遇到困难:
driver.pl
my $foo = MyApp::Boom->new( configfile => "/home/todd/text.cfg" );
MyApp::Boom
has configfile => (
is => 'ro', isa => 'Str', required => 1
);
has conf => (
is => 'ro', isa => 'HashRef', required => 1, lazy => 1,
builder => '_build_configuration'
);
sub _build_configuration {
my $self = shift;
unless ( $self->configfile ) {
die "No Configuration File!";
}
# stuff that reads the file and creates a hashref
return $href;
}
has baz => (
is => 'ro', isa => 'MyApp::Baz', required => 1, lazy => 1,
builder => '_build_baz',
);
sub _build_baz {
my $self = shift;
my $conf = $self->conf;
# uses data in conf to do stuff and create a MyApp::Baz
return MyApp::Baz->new($conf);
}
# other stuff omitted....
当我运行 driver.pl 时,有时会收到一条错误消息“无配置文件”,有时它可以工作。我显然遗漏了一些关于“懒惰”和“必需”的重要信息,但无法弄清楚。
我的理解是“configfile”将由 driver.pl 中的新调用设置,并且在其他地方调用时属性将初始化,并且可能已经设置了“configfile”。
欢迎提供指针、建议或替代方法。
【问题讨论】:
-
这显然不是你运行的代码...
-
我不明白这怎么可能工作,即使有时,除非你省略了一些方法
config访问$self->configfile。我认为_build_configuration()中有一个简单的错字:unless ( $self->config )应该是unless ( $self->configfile )。除此之外,conf上的required是多余的,因为它无论如何都是懒惰的,但也无妨。 -
还有
sub baz与属性baz的自动生成访问器,以及sub _build_baz的缺失。我同意@mbethke。这段代码不是你运行的。请不要在这里写新的代码。 Edit您的问题并显示您的真实代码,否则我们无能为力。 -
从运行的真实代码中提取(除了前面提到的问题),但遗憾的是由于无法进入此处的原因无法发布。抱歉,我试图将其简化为我认为问题所在的地方。问题的症结是一样的。我很快就会发布上面的工作版本。
-
减少代码也没关系(实际上,这是鼓励的!),但请在发布前将其变为实际运行的minimal reproducible example。