package Tie::Scalar::Lazy; # usage: # use Tie::Scalar::Lazy; # lazy $value => \&expensive_function; require Exporter; @ISA = qw( Exporter ); @EXPORT = qw( lazy ); sub lazy { tie $_[0], __PACKAGE__, \$_[0], $_[1]; } sub TIESCALAR { my ($class, $sref, $cref) = @_; bless [ $sref, $cref ], $class; } sub FETCH { my $self = shift; my $value = $self->[1]->(); untie ${ $self->[0] }; ${ $self->[0] } = $value; } 1;