Moose:构建器需要一个有时未设置的值(非确定性)

Moose: builder requires a value that sometimes is not set (non deterministic)

我是 MOOSE 和 Perl OOP 的新手,我很难理解代码的执行顺序。

我想创建一个class读取文件,所以对象的一个​​属性应该是文件句柄,另一个是要读取的文件名。

我的问题是属性 '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.