in reply to Simple Mouse/Moose question
So do_n(), the builder function, fires, then do_n2() fires "after". However, while do_n2() is provided with the object instance this instance does not contain the value for n which was initialized by the builder
Pretty much any time you want the builder/default of one attribute to have access to the values of another attribute, you want to use lazy. The order of attribute initialization in Moose (and Mouse) is undefined (basically hash-order). When you use lazy this allows the order to essentially be determined by the dependency chain itself. What you are doing here is pretty much more easily done like this:
which produces the following output:#!/usr/bin/perl -w use strict; package Test; use Mouse; has 'n' => (is => 'rw', isa => 'Int', lazy => 1, builder => 'do_n'); has 'n2' => (is => 'rw', isa => 'Int', lazy => 1, builder => 'do_n2'); sub do_n { my $s = shift; print "In do_n() \$s = $s\n"; return 3; } sub do_n2 { my $s = shift; print "In do_n2() \$s = $s\n"; return $s->n + 2; } __PACKAGE__->meta->make_immutable(); package main; use Data::Dumper; my $test = Test->new(); warn Dumper $test; $test->n2; warn Dumper $test;
$VAR1 = bless( {}, 'Test' ); In do_n2() $s = Test=HASH(0x861360) In do_n() $s = Test=HASH(0x861360) $VAR1 = bless( { 'n' => 3, 'n2' => 5 }, 'Test' );
-stvn
|
---|
Replies are listed 'Best First'. | |
---|---|
Re^2: Simple Mouse/Moose question
by ikegami (Patriarch) on Feb 23, 2011 at 01:50 UTC | |
by stvn (Monsignor) on Feb 24, 2011 at 15:26 UTC | |
Re^2: Simple Mouse/Moose question
by halfcountplus (Hermit) on Feb 23, 2011 at 13:50 UTC | |
by stvn (Monsignor) on Feb 24, 2011 at 15:50 UTC | |
by ikegami (Patriarch) on Feb 24, 2011 at 16:02 UTC |
In Section
Seekers of Perl Wisdom