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:
#!/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;
which produces the following output:
$VAR1 = bless( {}, 'Test' );
In do_n2() $s = Test=HASH(0x861360)
In do_n() $s = Test=HASH(0x861360)
$VAR1 = bless( {
'n' => 3,
'n2' => 5
}, 'Test' );
-
Are you posting in the right place? Check out Where do I post X? to know for sure.
-
Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
<code> <a> <b> <big>
<blockquote> <br /> <dd>
<dl> <dt> <em> <font>
<h1> <h2> <h3> <h4>
<h5> <h6> <hr /> <i>
<li> <nbsp> <ol> <p>
<small> <strike> <strong>
<sub> <sup> <table>
<td> <th> <tr> <tt>
<u> <ul>
-
Snippets of code should be wrapped in
<code> tags not
<pre> tags. In fact, <pre>
tags should generally be avoided. If they must
be used, extreme care should be
taken to ensure that their contents do not
have long lines (<70 chars), in order to prevent
horizontal scrolling (and possible janitor
intervention).
-
Want more info? How to link
or How to display code and escape characters
are good places to start.