Search code examples
perlmoose

How to die upon access to a uninitialized Moose object attribute?


I have a Moose object with a non-required attribute:

has 'optional_attr' => (
    is       => 'ro',
    isa      => 'MyCoolType',
    required => 0,
);

How can I confess if I ever try to read this attribute while it's not set?


Solution

  • How about:

    lazy    => 1,
    default => sub { confess "not set" },
    

    You might want to throw in a predicate, too:

    predicate => 'has_optional_attr',
    

    so you can find out if it's set without dying.

    There's also MooseX::LazyRequire, which lets you say just:

    use MooseX::LazyRequire;
    
    has 'optional_attr' => (
        is            => 'ro',
        isa           => 'MyCoolType',
        lazy_required => 1,
    );
    

    Under the hood, it uses the same trick I suggested, but it looks more elegant in your class.