Search code examples
perlmoosefilehandle

How do I set a default FileHandle attribute with moose


You may infer from the question that this is my first Moose class.

How do I set an attribute FileHandle to *STDOUT?

This doesn't work.

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

The output when run is:

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

The documentation claims:

FileHandle accepts either an IO::Handle object or a builtin perl filehandle (see "openhandle" in Scalar::Util).

What am I missing?

Thanks.

-E


Solution

  • I don't know what else you may need there, but this works for starters

    The 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;
    

    and the main

    use warnings;
    use strict;
    use feature 'say';
    
    use WithFH;
    
    my $wfh = WithFH->new;
    
    $wfh->say("hi"); 
    

    That prints hi to STDOUT.