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

标签 perl moose

我是 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/

相关文章:

java - OutputStream.write 太慢

perl - 更新 : Initialise and Clear multiple hash in one line

perl - 对 MooseX::Declare 的 ctags 支持? (Perl)

perl - 如何使Mason2 UTF-8干净?

perl - 如何防止在调用new时设置Perl Moose只读属性?

perl - 为什么Perl会警告我有关使用伪哈希的信息?

perl - 在 Perl 中取消引用数组键

windows - 为什么我的 Perl 单行程序不能在 Windows 上运行?

perl - 在Moose属性访问器上字符串重载的最佳方法是什么?

perl - 在构造过程中实例化强制属性