![]() | |
![]() |
![]() |
![]() | |
![]() | |
Caching and Persistence | |
![]() |
Sometimes I compute results that are expensive, so I like to hang onto them. This results is a blizzard of little temporary files, each with their own format, a writer, a reader, and some documentation. It is much better just to let perl remember the data. There are various Cache::Cache modules that help with this. My favorite is Cache::FileCache. Here is an example program that uses it:
#!/usr/bin/perl # use strict; use warnings; use diagnostics; use Cache::FileCache; my $name= "@ARGV"; my $cache = new Cache::FileCache({ 'namespace' => 'CustomerNames' }); my $customer = $cache->get( $name ); if ( not defined $customer ) { $customer = get_customer_from_lazy_clerk( $name ); $cache->set( $name, $customer, "10 minutes" ); } print "Yo! Customer $name is $customer\n"; sub get_customer_from_lazy_clerk { my ($cust_name)= @_; print "I'm so sleepy... I must sleep now!\n"; sleep int(rand(5)+2); my $cust= 'Mr. '.$cust_name; print "Now I remember, $cust_name 's name is $cust\n"; return $cust; }
There are many other functions that allow you to specify how long items last in the Cache before being deleted, how large the cache can get, and more. There are also functions to purge the cache right away and do all the other cache management functions. See the documentation for both Cache::FileCache and Cache::Cache.
Other ways to get (file-based) persistence:
Other ways to get caching: