| Computers Forum Index » Computer Languages (Perl - Modules) » Module for storing hash of strings to a file. ... |
|
Page 1 of 1 |
|
| Author |
Message |
| Jerry Krinock... |
Posted: Sun Oct 18, 2009 5:29 am |
|
|
|
Guest
|
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' ;
etc.
The strings may contain unicode characters. Is this a job for a Tie:
module?
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?
Sincerely,
Jerry Krinock |
|
|
| Back to top |
|
|
|
| Tad J McClellan... |
Posted: Sun Oct 18, 2009 9:45 am |
|
|
|
Guest
|
Jerry Krinock <jerrykrinock at (no spam) gmail.com> wrote:
Quote: I'd like to store a hash of several hundred abbreviations of strings
to a file on disk.
You want a "persistent" data structure...
perldoc -q persist
How do I keep persistent data across program calls?
Quote: Which module should I study for
this simple job?
perldoc Storable
--
Tad McClellan
email: perl -le "print scalar reverse qq/moc.noitatibaher\100cmdat/" |
|
|
| Back to top |
|
|
|
| Jerry Krinock... |
Posted: Mon Oct 19, 2009 2:49 am |
|
|
|
Guest
|
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
'Storable'
returns: A reference to the hash, or an empty hash if no file exists
at the given path.
=cut
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
=cut
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) ;
}
} |
|
|
| Back to top |
|
|
|
|