Beefy Boxes and Bandwidth Generously Provided by pair Networks
No such thing as a small change
 
PerlMonks  

Re: Moose constructor help

by kennethk (Abbot)
on Mar 13, 2014 at 15:23 UTC ( #1078187=note: print w/replies, xml ) Need Help??


in reply to Moose constructor help

You can do that using a default; if I assume you want $results to be a function of $contents, it might look like (untested):
use Moose; use JSON; has content => isa => 'Str', is => 'ro', required=> 1, ; has results => isa => 'Str', is => 'ro', default => sub { decode_json($_[0]->content) }, ;
There are a lot of variations how that would look depending on what you actually intend to do. See Default and builder methods in Moose::Manual::Attributes for more details.

#11929 First ask yourself `How would I do this without a computer?' Then have the computer do it the same way.

Replies are listed 'Best First'.
Re^2: Moose constructor help
by greengaroo (Hermit) on Mar 14, 2014 at 18:34 UTC

    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?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others meditating upon the Monastery: (6)
As of 2016-10-01 07:05 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    Extraterrestrials haven't visited the Earth yet because:







    Results (575 votes). Check out past polls.