Alister West

home is where your code is ...

Perl Caching

DB_File is a Perl 5 core module that uses BDB (Berkeley DB) as a backend. DB_File is great - but you can only store scalars so you will need to serialise more complex data (Storable,JSON,etc.). Or you can use MLDBM which does it for you.

Simple Tied Hash

# Use just like a hash - but with persistance!
# DB_File only stores scalars, so use MLDBM to serialise for you!

use Fcntl; # O_CREAT..
use MLDBM qw(DB_File Storable);

my %CACHE;
my $cache_file = "$ENV{HOME}/cache.bdb";
tie %CACHE, "MLDBM", $cache_file, O_CREAT|O_RDWR, 0666
    or die "Cannot open $cache_file: $!\n";

$CACHE{foo} = "TheFoo"; # set
my $foo = $CACHE{foo};  # get
delete $CACHE{foo};     # delete

Simple Tied Hash as a Cache Module

package Local::Cache;

use Fcntl; # O_CREAT.. 
use MLDBM qw(DB_File Storable);

our %CACHE; # singleton tied hash

sub get { my ($k) = @_; return $CACHE{$k}; }
sub set { my ($k, $v) = @_; return $CACHE{$k} = $v; }

sub new {
    my ($class, $filename) = @_;
    $filename ||= "$ENV{HOME}/cache.bdb";
    tie %CACHE, "MLDBM", $filename, O_CREAT|O_RDWR, 0666
        or die "Cannot open $filename: $!\n";
    return bless \%CACHE, $class;
}

package main;

my $cache = Local::MyCache->new("/tmp/cachefile.db");
$cache->set("foo", "bar");
$cache->get("foo");


1;
By Alister West