我是 MOOSE 和 Perl OOP 的新手,我很难理解代码的执行顺序。
我想创建一个读取文件的类,所以对象的一个属性应该是文件句柄,另一个是要读取的文件名。
我的问题是属性“filehandle”有一个需要 $self->filename 的构建器,但有时在运行时调用构建器时“filename”不(还)可用。
谢谢你的帮助
我理想的对象创建:
my $file = FASTQ::Reader->new(
filename => "$Bin/test.fastq",
);
Perl 模块:
has filename => (
is => 'ro', isa => 'Str', required => 1,
);
has fh => (
is => 'ro', isa => 'FileHandle', builder => '_build_file_handler',
);
sub _build_file_handler {
my ($self) = @_;
say Dumper $self;
open(my $fh, "<", $self->filename) or die ("cant open " . $self->filename . "\n");
return $fh;
}
参见:https://gist.github.com/telatin/a81a4097913af55c5b86f9e01a2d89ae
最佳答案
如果一个属性的值依赖于另一个属性,让它成为惰性的。
#!/usr/bin/perl
use warnings;
use strict;
{ package My::Class;
use Moose;
has filename => (is => 'ro', isa => 'Str', required => 1);
has fh => (is => 'rw', isa => 'FileHandle', lazy => 1, builder => '_build_fh');
# ~~~~~~~~~
sub _build_fh {
my ($self) = @_;
open my $fh, '<', $self->filename or die $!;
return $fh
}
}
my $o = 'My::Class'->new(filename => __FILE__);
print while readline $o->fh;
参见 Laziness in Moose::Manual::Attributes :
if the default value for this attribute depends on some other attributes, then the attribute must be
lazy
.
关于perl - Moose:构建器需要一个有时未设置的值(非确定性),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55973274/