Beefy Boxes and Bandwidth Generously Provided by pair Networks
Problems? Is your data what you think it is?

Re^2: Moose constructor help

by greengaroo (Hermit)
on Mar 14, 2014 at 18:34 UTC ( #1078379=note: print w/replies, xml ) Need Help??

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.

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://1078379]
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others imbibing at the Monastery: (2)
As of 2018-02-18 23:38 GMT
Find Nodes?
    Voting Booth?
    When it is dark outside I am happiest to see ...

    Results (257 votes). Check out past polls.