Re: Set attribute using 'after'

[email protected] (Karen Etheridge)
Newsgroups perl.moose
Message-ID <[email protected]>
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, [email protected]       GCS C+++$ USL+++$ P+++$ w--- M++
lmpx.com only provides a reader for public news (NNTP) servers. It is not affiliated with the servers or forums shown here and is not responsible for the content of articles, which is written by their respective authors.