0

I'm having difficulty with attribute initialization order in the following:

driver.pl

my $foo = MyApp::Boom->new( configfile => "/home/todd/text.cfg" );

MyApp::Boom

has configfile => (
    is    => 'ro', isa => 'Str', required => 1
);

has conf => (
    is => 'ro', isa => 'HashRef', required => 1, lazy => 1,
    builder => '_build_configuration'
);

sub _build_configuration {
    my $self = shift;

    unless ( $self->configfile ) {
        die "No Configuration File!";
    }
    # stuff that reads the file and creates a hashref
    return $href;
}

has baz => (
    is => 'ro', isa => 'MyApp::Baz', required => 1, lazy => 1,
    builder => '_build_baz',
);

sub _build_baz {
    my $self = shift;
    my $conf = $self->conf;
    # uses data in conf to do stuff and create a MyApp::Baz
    return MyApp::Baz->new($conf);
}

# other stuff omitted....

When I run the driver.pl, I sometimes get an error message "No Configuration File" and sometimes it works. I'm obviously missing something important about 'lazy' and 'required', but can't figure it out.

My understanding is the "configfile" would be set by the new call in driver.pl and the the attributes would initialize when called elsewhere and presumably 'configfile' would already be set.

Pointers, recommendations, or alternative approaches are welcome.

Todd
  • 698
  • 6
  • 19
  • This is obviously not the code you ran... – ikegami May 12 '16 at 02:42
  • 1
    I don't see how this could possibly work even sometimes unless you omitted some method `config` that acceses `$self->configfile`. I think there's a simple typo in `_build_configuration()`: `unless ( $self->config )` should be `unless ( $self->configfile )`. Other than that, the `required` on `conf` is superfluous as it is lazy anyway, but it doesn't hurt either. – mbethke May 12 '16 at 02:48
  • 1
    There is also the `sub baz` vs the auto-generated accessor for the property `baz`, and the absence of `sub _build_baz`. I agree with @mbethke. This code is not what you ran. Please don't write fresh code in here. [Edit] your question and show your **real** code, or we cannot help. – simbabque May 12 '16 at 10:00
  • Extracted from real code that runs (except for the aforementioned problem), but unfortunately unable to post it for reasons I am unable to go into here. Sorry I tried to simplify it down to where I believe the problem lies. The crux of the problem is the same. I will post a working version of above shortly. – Todd May 12 '16 at 15:39
  • It's fine to reduce your code (actually, it's encouraged!), but please make it into a [mcve] that actually runs before posting. – ThisSuitIsBlackNot May 12 '16 at 15:53

1 Answers1

0

Thanks for the help everyone. I ran the real code line by line through the debugger and found that there was one attribute buried in a subclass that didn't have lazy=>1.

Todd
  • 698
  • 6
  • 19