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.
Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
Read Where should I post X? if you're not absolutely sure you're posting in the right place.
Please read these before you post! —
Posts may use any of the Perl Monks Approved HTML tags:
- a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
| |
For: |
|
Use: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.