home | O'Reilly's CD bookshelfs | FreeBSD | Linux | Cisco | Cisco Exam  


Book HomeProgramming the Perl DBISearch this book

2.8. 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.[19]

[19]We discussed serialization and the Data::Dumper and Storable modules earlier in this chapter.

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 megalith records in the database
%database1 = (
    'Avebury' => {
        name => 'Avebury',
        mapref => 'SU 103 700',
        location => 'Wiltshire'
    },
    'Ring of Brodgar' => {
        name => 'Ring of Brodgar',
        mapref => 'HY 294 133',
        location => 'Orkney'
    }
);

### Untie and retie to show data is stored in the file
untie %database1;

tie my %database2, 'MLDBM', 'mldbmtest.dat', O_RDWR, 0666
    or die "Can't initialize MLDBM file: $!\n";

### Dump out via Data::Dumper what's been stored ...
print Data::Dumper->Dump( [ \%database2 ] );

untie %database2;

exit;

The results of running this program are:

$VAR1 = {
      'Avebury' => {
                     'name' => 'Avebury',
                     'location' => 'Wiltshire',
                     'mapref' => 'SU 103 700'
                   },
      'Ring of Brodgar' => {
                             'name' => 'Ring of Brodgar',
                             'location' => 'Orkney',
                             'mapref' => 'HY 294 133'
                           }
    };

This shows that the nested data within the original hash has been restored intact.



Library Navigation Links

Copyright © 2001 O'Reilly & Associates. All rights reserved.