This is so small compared to the rest of the posts here in CUFP, I hesitated for a while before deciding to submit anyway:
package cache {
# no particular reason to use them,
# but the syntax sugar is *so* sweet
use experimental 'signatures';
use base 'Storable';
my %paths;
sub new($class,$path) {
my $self = eval { return Storable::retrieve($path) }
|| bless {}, $class;
$paths{$self} = $path;
return $self;
}
sub DESTROY($self) {
$self->store($paths{$self});
}
}
How to use:
- create the object as you usually would: my $cache = cache::->new("store.db");
- anywhere you might find it useful to cache results in a hash between runs of a function, use defined-or assignment to retrieve the value if it's already cached: my $val = $cache->{$argument} //= func($argument);
- next time you run the script again the cached values are still there, no need to recalculate
- combine with memoization for best results
The class uses
inside-out objects so you could use objects as ordinary hashes with no reserved fields. This will get slower the bigger your cache gets because there is no RLU eviction, everything is stored in memory and the whole store has to be loaded from disk on startup and serialised on shutdown. Still, for small scripts I find it useful.