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:
My output is this:use lib '.'; use Foo::Bar; use Data::Dumper; my $o = Foo::Bar->new; print STDERR Dumper($o);
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
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |