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

And*_* T. 3 perl moose

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

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

我的问题是属性'filehandle' 有一个需要$self->filename 的构建器,但有时在运行时'filename' 在调用构建器时(还)不可用。

谢谢你的帮助

我理想的对象创建:

my $file = FASTQ::Reader->new(
    filename => "$Bin/test.fastq",
);
Run Code Online (Sandbox Code Playgroud)

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;
}
Run Code Online (Sandbox Code Playgroud)

参见:https : //gist.github.com/telatin/a81a4097913af55c5b86f9e01a2d89ae

cho*_*oba 5

如果一个属性的值依赖于另一个属性,请将其设为惰性。

#!/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;
Run Code Online (Sandbox Code Playgroud)

参见Moose::Manual::Attributes 中的懒惰

如果此属性的默认值取决于某些其他属性,则该属性必须lazy