Module for storing hash of strings to a file. Tie:...?

Do you have a question? Post it now! No Registration Necessary.  Now with pictures!

Threaded View

I'd like to store a hash of several hundred abbreviations of strings
to a file on disk.  Something like:

$abbrevs{'Strawberry Banana'} = 'strawBan' ;
$abbrevs{'Cream Cheese'} = 'crmChz' ;

The strings may contain unicode characters.  Is this a job for a Tie:

All the Tie: modules seem quite complicated and specialized, and I
don't quite understand perltie yet.  Which module should I study for
this simple job?


Jerry Krinock

Re: Module for storing hash of strings to a file. Tie:...?

Quoted text here. Click to load it

You want a "persistent" data structure...

    perldoc -q persist

        How do I keep persistent data across program calls?

Quoted text here. Click to load it

    perldoc Storable

Tad McClellan
email: perl -le "print scalar reverse qq/moc.noitatibaher0cmdat/"

Re: Module for storing hash of strings to a file. Tie:...?

Thanks, Tad.  Nice that 'Storable' is already on my computer.

I found that Storable:retrieve() was a bit annoying because it dies
your script if the referenced storage file does not exist, or if the
file does exist but was store()d with an empty hash.  I wrote a couple
of wrapper functions to make Storable easier to use.  Maybe some
archive-searcher will find these useful:

use File::Util ;
use Storable ;

=item retrieveFromStorage()

Gets a hash from disk storage, using module 'Storable'.
param1: filesystem path of data previously stored by storeToStorage or
returns: A reference to the hash, or an empty hash if no file exists
at the given path.

sub retrieveFromStorage {
    my $path = shift ;
    my $fileUtil = File::Util->new() ;
    my $hashRef ;
    if ($fileUtil->existent($path)) {
        print "Retrieving data at $path.\n" ;
        $hashRef = Storable::retrieve($path) ;
    else {
        print "Creating empty hash because no stored data at $path.
\n" ;
        $hashRef = {} ;

    return $hashRef ;

=item storeToStorage()

Stores a hash to disk, using module 'Storable'.
If there are no key/values in given hash, deletes file at given path,
if any.  (This is so that Storable::retrieve will not find an empty
file and cause script to die.)

param1: Reference to hash to be stored
param2: filesystem path at which to store the hash


sub storeToStorage {
    my $hashRef = shift ;
    my $path = shift ;
    if (keys %$hashRef > 0) {
        my $ok = Storable::store($hashRef, $path) ;
        if (!$ok) {
            print "Could not store data at $path.\n" ;
    else {
        print "No data to store.  Removing $path.\n" ;
        unlink($path) ;

Site Timeline