http://qs321.pair.com?node_id=374384

jryan has asked for the wisdom of the Perl Monks concerning the following question:

Just a small question: does a module to laziliy initialize a tied variable exist on the CPAN? Basically, I have a bunch class variables that are each initialized separately by a relatively expensive operation (database access, reading in an xml file, etc). Since I'm not programming Java, I would feel silly creating a separate Singleton class for each one of these things. All I really want to do is use them like normal variables, and just have them become magically initialized during their first use. As a quick first rev, I hacked this up:

package Tie::LazyInitialized::Hash; use strict; require Tie::Hash; our @ISA = 'Tie::StdHash'; my $sub; sub TIEHASH { my ($class, $callback, @args) = @_; $sub = sub { $callback->(@args) }; bless {}, $class; } sub FETCH { my ($self, $key) = @_; %$self = %{ $sub->() } unless %$self; # hehe, i wonder if %&$sub w +ould work? $self->{$key} } 1;

But, as soon as I finished typing the last ;, I figured that there *must* be a general CPAN module to do this. However, given that not being able to find things on CPAN is something of a knack of mine, I haven't found anything like what I need. I'd much-much-much rather use a CPAN module than this little hacked up thing. Does anyone know if one exists?