If you don't use a particular data member, why define it?
Luckily, Perl gives us a way to delay processing a piece of data until we really need it.
As an example, try the following:#!/usr/bin/perl -w use strict; package TieLazy; use Tie::Hash; @TieLazy::ISA = qw( Tie::StdHash ); sub new { my $class = shift; my %data; tie %data, "TieLazy", @_; bless \%data, $class; } sub TIEHASH { my $self = shift; my %data = %{ +shift }; bless \%data, $self; } sub FETCH { my $self = shift; my $item = shift; if (defined(my $data = ($self->{$item}))) { if (ref($data) eq 'CODE') { return $self->{$item} = $data->(); } else { return $self->{$item}; } } }
The constructor takes an anonymous hash. Keys become the name of the object's attributes. The values should be literal values (if not calculated only when accessed) or subroutine references which process and return the data.sub do_two { print "Doing two!\n"; return 2; } my $tl = TieLazy->new({one => 1, two => \&do_two}); print join("\t", @$tl{qw( one two two )} ), "\n"; $tl->{three} = 3; print "$$tl{three}\n"; $tl->{four} = sub { print "Four!\n"; return 4; }; print "Four exists!\n" if (exists($tl->{four})); print "$$tl{four}\n"; print "$$tl{four}\n";
The first time you access an element, the object will run the code reference and store and return the result. All subsequent accesses just use a simple retrieval.
Possible modifications include not deleting the original sub ref, which would allow a DELETE sub to clear out the data value, allowing it to be recalculated on the next access. Each value in the hash should probably hold a two-element anonymous array ([ data, code_ref ]).
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Delayed Data Generation
by merlyn (Sage) on Jan 05, 2001 at 06:29 UTC |