develooper Front page | perl.moose | Postings from May 2012

Re: Set attribute using 'after'

Thread Previous | Thread Next
From:
Jesse Luehrs
Date:
May 11, 2012 07:34
Subject:
Re: Set attribute using 'after'
Message ID:
20120511143407.GP4502@tozt.net
On Fri, May 11, 2012 at 08:30:13AM -0600, Curtis Jewell wrote:
> On Fri, May 11, 2012, at 15:42, Emmanuel Quevillon wrote:
> > Hi,
> > 
> > I got an exception when using 'after' this way.
> > Here is my Moose class :
> > 
> > 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;
> 
> You don't have a 'new' attribute to hook 'after'.
> 
> The technical name for "after 'new' => sub {" is "sub BUILD {". See
> Moose::Cookbook::Basics::Person_BUILDARGSAndBUILD for more details.

'after' modifies methods, not attributes. after 'new' is valid, although
not recommended (using BUILD is the right answer to the actual
question). The exception is caused because 'after' modifiers are called
with the original arguments, so $self there is still the string
'MyClass', not an instance that you can call attribute accessors on.

-doy

Thread Previous | Thread Next


nntp.perl.org: Perl Programming lists via nntp and http.
Comments to Ask Bjørn Hansen at ask@perl.org | Group listing | About