驼鹿:构建器需要有时未设置的值(不确定)

时间:2019-05-03 15:50:16

标签: 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

1 个答案:

答案 0 :(得分:4)

如果一个属性的值依赖于另一个属性,请使其变得懒惰。

lazy

请参见Laziness in Moose::Manual::Attributes

  

如果此属性的默认值取决于其他一些属性,则属性必须const source = [1,3,6]; /** * @method nrOfMissedItems * @param {Array<Number>} an array containing only numbers * @returns -Infinity when the parameter arr is null or undefined, otherwise number of non-mentioned numbers, ie [5,5] returns 0, [1,1,1,3] returns 1 * When the array contains non-numbers it will return NaN */ function nrOfMissedItems( arr ) { const noDuplicates = [...new Set(arr)]; const highestNumber = Math.max( ...noDuplicates ); const lowestNumber = Math.min( ...noDuplicates ); return highestNumber - lowestNumber - noDuplicates.length + 1; } console.log( nrOfMissedItems( source ) ); // 3 console.log( nrOfMissedItems( [1] ) ); // 0 console.log( nrOfMissedItems( [0,1,4] ) ); // 2 console.log( nrOfMissedItems( [5,3,1] ) ); // 2 console.log( nrOfMissedItems( [1,1,1,1,5] ) ); // 3 console.log( nrOfMissedItems( null ) ); // -Infinity console.log( nrOfMissedItems( undefined ) ); // -Infinity console.log( nrOfMissedItems() ); // -Infinity console.log( nrOfMissedItems( ['a','b', 1] ) ); // NaN console.log( nrOfMissedItems( ['a', null, 1] ) ); // NaN console.log( nrOfMissedItems( [undefined, 1] ) ); // NaN