Beefy Boxes and Bandwidth Generously Provided by pair Networks
We don't bite newbies here... much
 
PerlMonks  

A hash that stores itself between runs

by Anonymous Monk
on Sep 06, 2018 at 14:53 UTC ( [id://1221886]=CUFP: print w/replies, xml ) Need Help??

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.

Replies are listed 'Best First'.
Re: A hash that stores itself between runs
by Jenda (Abbot) on Sep 27, 2018 at 12:17 UTC

      Right, BerkeleyDB and friends. Thank you for reminding me.

      I could provide excuses like "but that one only stores strings" or "but I don't want to pull outside dependencies" or "but it's only a dozen lines or so"... there are many solutions like it, but this one is mine. Don't worry, I'm not a professional programmer.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: CUFP [id://1221886]
Approved by Corion
Front-paged by Discipulus
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others drinking their drinks and smoking their pipes about the Monastery: (3)
As of 2026-01-23 05:03 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    What's your view on AI coding assistants?





    Results (125 votes). Check out past polls.

    Notices?
    hippoepoptai's answer Re: how do I set a cookie and redirect was blessed by hippo!
    erzuuliAnonymous Monks are no longer allowed to use Super Search, due to an excessive use of this resource by robots.