[Wellington-pm] DBM tied hash example

Grant McLean grant at mclean.net.nz
Tue May 10 16:45:24 PDT 2016


Further to my brief aside on using a tied hash as a crude IPC mechanism
to allow multiple independent scripts to communicate via shared state,
I've pasted an example script below.

When invoked like this:

  ./tied-hash-example day Wednesday

It will set the 'day' key in the hash to 'Wednesday'.

You could retrieve the value of the 'day' key like this:

  ./tied-hash-example day

Or dump all the keys like this:

  ./tied-hash-example

The script doesn't have an example of deleting a key but you can just do
that using Perl's built-in 'delete' function.

Cheers
Grant


#!/usr/bin/perl

use 5.014;
use strict;
use warnings;
use autodie;

use Fcntl qw(O_RDWR O_CREAT :flock);
use SDBM_File;

my $db_file   = '/home/grant/state.db';
my $fh_lock;
my %state_db;

tie_db_file($db_file);

if(@ARGV > 1) {                 # Put key/values into DB
    while(@ARGV) {
        my $key = shift;
        $state_db{$key} = shift;
    }
}
elsif(@ARGV == 1) {             # Print out one value
    my $key = shift;
    say "$key=$state_db{$key}";
}
else {                          # Dump all values
    foreach my $key (sort keys %state_db) {
        say "$key=$state_db{$key}";
    }
}

untie_db_file();

exit;


sub tie_db_file {
    my($filename) = @_;
    open $fh_lock, '>>', $filename . '.lck';
    flock($fh_lock, LOCK_EX);
    tie(%state_db, 'SDBM_File', $filename, O_RDWR|O_CREAT, 0660);
}

sub untie_db_file {
    untie %state_db;
    flock($fh_lock, LOCK_UN);
}





More information about the Wellington-pm mailing list