On Fri, May 11, 2012 at 03:42:15PM +0200, Emmanuel Quevillon wrote:
> package Myclass;
> 
> use Moose;
> extends 'SuperClass';
> with 'MyRole';
> 
> has 'file' => (is => 'rw', isa => 'Str', required => 1);
> has 'fh'   => (is => 'rw', isa => 'FileHandle');
> 
> after 'new' => sub {
>    my $self = shift;
>    my $file = $self->file();
>    $self->set_fh($self->open_file($file)); # Returns a FileHandle obj
>    return 0;
> };
> 
> 1;

Why not just create the filehandle when it's first needed, rather than at
construction time?  (that is: let the attribute build itself, rather than
explicitly calling a setter).

has fh => (
    is => 'ro', isa => 'FileHandle',
    lazy => 1,
    default => sub {
        my $self = shift;
        $self->open_file($self->file);
    },
);

or, you can skip the extra attribute entirely by using library code:

use MooseX::Types::Path::Class qw(Dir File);
has file => (
    is => 'ro', isa => File,
    coerce => 1,
);

# later, in other code...
# $self->file isa Path::Class::File
my $fh = $file->openr;

# or skip using the fh directly...
my $contents = $self->file->slurp;

my $filename = $self->file->stringify;

# etc etc...


-- 
             Don't anthromoporphize computers.  They _hate_ that!
            .             .            .            .             .
Karen Etheridge, ka...@etheridge.ca       GCS C+++$ USL+++$ P+++$ w--- M++

Reply via email to