The MLDBM Module
The
MLDBM
module is very
useful for quickly writing complex Perl data structures to DBM files
for persistent storage. The ML
in
MLDBM
stands for multilevel
and refers to its ability to store complex multilevel data
structures. That’s something that ordinary hashes, even hashes
tied to DBM files, can’t do.
The
MLDBM
module is an
excellent example of a layered storage manager. It acts as a thin
layer over another DBM module, but intercepts reads and writes to
automatically
serialize
(or deserialize) the data using another module.[18]
The module works by automatically serializing the Perl data
structures that you wish to store into a single string, which is then
stored within a DBM file. The data is recovered by deserializing the
data from the stored string back into a valid Perl object. The actual
interface for referencing the stored and retrieved data is identical
to the API for DBM files. That makes it very easy to “drop
in” use of MLDBM
instead of your existing
DBM module.
The following example shows how we could use
DB_File
for storage and
Data::Dumper
for displaying the restored data:
#!/usr/bin/perl -w # # ch02/mldbmtest: Demonstrates storing complex data structures in a DBM # file using the MLDBM module. use MLDBM qw( DB_File Data::Dumper ); use Fcntl; ### Remove the test file in case it exists already ... unlink 'mldbmtest.dat'; tie my %database1, 'MLDBM', 'mldbmtest.dat', O_CREAT | O_RDWR, 0666 or die "Can't initialize MLDBM file: $!\n"; ### Create some ...
Get Programming the Perl DBI 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.