Search code examples
perllazy-evaluationmoose

Moose object as a lazy hash


I want to replace some hashes used in my program with lazy Moose objects for performance reason. The problem is, there's a lot of code that I don't control that uses, of course, ->{key} to access elements. Such access works with Moose objects, but does not work with lazy ones before they were initialized:

package Stuff;

use Moose;

has foo => (
   lazy=>1, 
   default=> sub { +{bar=>baz} }
);

package main;
my $x = Stuff->new();

print Dumper $x->{foo}; # undef =(
print Dumper $x->foo;   # {bar => baz }
print Dumper $x->{foo}; # {bar => baz }

Any way to make that first $x->{foo} initialize the variable?


Solution

  • You can't use it as a hash directly, but with Tie::Moose you can create a hash which calls the underlying Moose methods. You can pass this hash along to your other code.

    use Tie::Moose;
    
    my $x = Stuff->new();
    tie my %x, "Tie::Moose", $x;
    
    print Dumper($x{foo}); # { 'bar' => 'baz' }