Storing Complex Data in a DBM File
Problem
You want values in a DBM file to be something other than scalars. For instance, you use a hash of hashes in your program and want to store them in a DBM file for other programs to access, or you want them to persist across process runs.
Solution
Use the CPAN module MLDBM to store more complex values than strings and numbers.
use MLDBM 'DB_File'; tie(%HASH, 'MLDBM', [... other DBM arguments]) or die $!;
Discussion
MLDBM uses Data::Dumper (see Section 11.14) to convert data structures to and from strings so that they can be stored in a DBM file. It doesn’t store references, instead it stores the data that the references refer to:
# %hash is a tied hash
$hash{"Tom Christiansen"} = [ "book author", 'tchrist@perl.com' ];
$hash{"Tom Boutell"} = [ "shareware author", 'boutell@boutell.com' ];
# names to compare
$name1 = "Tom Christiansen";
$name2 = "Tom Boutell";
$tom1 = $hash{$name1}; # snag local pointer
$tom2 = $hash{$name2}; # and another
print "Two Toming: $tom1 $tom2\n";
Tom Toming: ARRAY(0x73048) ARRAY(0x73e4c)
Each time MLDBM retrieves a data structure from the DBM file, it generates a new copy of that data. To compare data that you retrieve from a MLDBM database, you need to compare the values within the structure:
if ($tom1->[0] eq $tom2->[0] && $tom1->[1] eq $tom2->[1]) { print "You're having runtime fun with one Tom made two.\n"; } else { print "No two Toms are ever alike.\n"; }
This is more efficient than:
if ($hash{$name1}->[0] eq $hash{$name2}->[0] ...
Get Perl Cookbook now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.