Beefy Boxes and Bandwidth Generously Provided by pair Networks
The stupid question is the question not asked
 
PerlMonks  

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.


Comment on Re^2: Moose constructor help
Select or Download Code

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://1078379]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others avoiding work at the Monastery: (9)
As of 2014-12-18 07:41 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    Is guessing a good strategy for surviving in the IT business?





    Results (44 votes), past polls