in reply to Re: Moose constructor help
in thread Moose constructor help

I'm not sure why you would need this in the constructor, but altering a little the example from kennethk, this is how I would do it:

use Moose; use JSON; has content => ( isa => 'Str', is => 'ro', required=> 1, ); has results => ( isa => 'Str', is => 'ro', lazy => 1, builder => '_build_results', ); sub _build_results { my $self = shift; return decode_json($self->content); }

With lazy and builder, the results attribute will be populated only when needed, only when you call $obj->results()

Note: the builder method has access to $self, the reference to the instance, because it is called AFTER the instance is created, however, in kennethk's example, I don't think the default sub has access to $self or in this case $_[0]* because the default sub is executed WHILE the instance is being created, therefore, the reference is not yet available.

* In a method, $_[0] contains the reference to the instance, same as if you do my $self = shift; or my $self = shift(@_); or my $self = $_[0];. I may be mistaking but I've had problems with this before and since then, I use lazy attributes with a builder method.

A for will get you from A to Z; a while will get you everywhere.