如何使用moose设置默认的FileHandle属性

问题描述 投票:2回答:1

你可以从问题中推断出这是我的第一个穆斯班。

如何将属性FileHandle设置为* STDOUT?

这不起作用。

has 'output' => (
is => 'rw',
isa => 'FileHandle',
default => sub { openhandle(*STDOUT) }
);

运行时的输出是:

Attribute (output) does not pass the type constraint because: Validation failed for 'FileHandle' with value *main::STDOUT

文件声称:

FileHandle接受IO :: Handle对象或内置perl文件句柄(请参阅Scalar :: Util中的“openhandle”)。

我错过了什么?

谢谢。

-E

perl moose
1个回答
2
投票

我不知道你还需要什么,但这适合初学者

WithFH.pm

package WithFH;

use feature 'say';
use Moose;

has 'fh' => (is => 'ro', isa => 'FileHandle', default => sub { \*STDOUT } );

sub say {
    my $self = shift;
    say { $self->{fh} } "@_";
}

__PACKAGE__->meta->make_immutable;    
1;

和主要的

use warnings;
use strict;
use feature 'say';

use WithFH;

my $wfh = WithFH->new;

$wfh->say("hi"); 

hi打印到STDOUT

© www.soinside.com 2019 - 2024. All rights reserved.