Hello monks, I'm back with a Moose question that's causing me some head scratching. I have the following code:

package Foo; use Moose; has 'y' => ( is => 'Num', is => 'rw' ); has 'x' => ( is => 'Num', is => 'rw' ); sub init_y { my ($self, $value) = @_; $self->y(sqrt($self->x)); } sub BUILD { my ($self) = @_; print STDERR "Foo::BUILD running\n"; $self->init_y; } 1;

And:

package Foo::Bar; use Moose; extends 'Foo'; before 'BUILD' => sub { my $self = shift; print STDERR "Foo::Bar before BUILD running\n"; $self->x(25); }; 1;

And my test script:

use lib '.'; use Foo::Bar; use Data::Dumper; my $o = Foo::Bar->new; print STDERR Dumper($o);
My output is this:
plxc16479> ex.pl Foo::BUILD running Use of uninitialized value in sqrt at Foo.pm line 17. Foo::Bar before BUILD running Foo::BUILD running $VAR1 = bless( { 'y' => '5', 'x' => 25 }, 'Foo::Bar' );

So, my question is...why am I seeing Foo::BUILD execute twice? My guess is that Foo::Bar is inheriting Foo's BUILD method...meaning there is now Foo::Build and Foo::Bar::BUILD. The base Foo::Build executes. Since Foo::Bar has a before BUILD modifier, and an inherited BUILD method, Foo::Bar before BUILD is executed before the subclass Foo::Bar::BUILD...but after Foo::BUILD has already done its thing.

Assuming this is the case, how do I get the behavior that I want? The idea is that Foo::Bar can modify the way Foo initializes by presetting 'x' to a particular value. However, I seem unable to do this with a sub class before Foo::BUILD executes. Here, that results in a warning but it can definitely result in problems in real code.


In reply to Moose and BUILD by tj_thompson

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.