in reply to Re: Moose and BUILD
in thread Moose and BUILD

It looks like maybe a better way to do this is to instead hook into BUILDARGS as this is executed before the object is created and allows for argument modification. I could explicitly set the value of x passed into the BUILD method and set an empty build method for Foo::Bar.

Replies are listed 'Best First'.
Re^3: Moose and BUILD
by tj_thompson (Monk) on Jun 15, 2011 at 20:58 UTC
    Modifying Foo::Bar to this:
    package Foo::Bar; use Moose; extends 'Foo'; use Data::Dumper; around 'BUILDARGS' => sub { my ($orig, $class, %args) = @_; print STDERR "Foo::Bar::BUILDARGS running.\n"; $args{x} = 25; return $class->$orig(%args); }; 1;

    Seems to do what I want. Foo::BUILD is only executed once and it receives the updated 'x' value prior to BUILD execution, so 'y' is only calculated once. Here is the output in this case:

    plxc16479> ex.pl Foo::Bar::BUILDARGS running. Foo::BUILD running $VAR1 = bless( { 'y' => '5', 'x' => 25 }, 'Foo::Bar' );