Tie a Yellow Ribbon ...
December 18, 2000
On several occassions we've said that you can "tie" a hash to a
disk-based file. In fact, to "tie" a hash means something specific in
Perl. To use any of the DBM's we've talked about, one must first tie
a hash to the DBM manager. So far we've done this using
dbmopen, which itself actually calls the tie function. But
that only works for the standard ODBM/NDBM database -- if we want to
use any of the fistful of alternative DBM's, we must learn to tie on
our own. No more clip-ons.
Suppose SDBM is attractive for a particular project, because we
have a large hash with small values -- which plays right into SDBM's
hand. Tie-ing a hash to any DBM follows a standard template that we
can illustrate using SDBM.
use SDBM;
use Fcntl;
my %car=();
tie (%car, "SDBM", "car_data", O_CREAT|O_RDWR, 0666) ||
die "Could not open or create database.";
%car = ( 'make' => 'Nissan',
'model' => 'Maxima',
'year' => '1997',
'color' => 'evergreen'
);
untie (%car);
Two use statements begin this code, as we include the SDBM
module and the Fcntl module for filesystem control. Some Perl
distributions may not include SDBM, or other alternative DBM's, so
this or other DBM modules may need to be installed separately. The
Fcntl module gives us some keywords that we'll use with the
tie function.
The %car hash is initialized and then the tie call
is made. The syntax of tie should certainly recall
dbmopen. Following the hash name, we specify the DBM module being
used ("SDBM") and the filename for the disk-based file ("car_data").
Next we list some keywords, courtesy of Fcntl, that specify the mode
for this file. Specifically, O_CREAT will create the file anew if it
doesn't yet exist, while O_RDWR will allow reading or writing to and
from the file.
If, instead, we know that the database file exists and we want
read-only access -- no modification will be made to the hash -- we
can leave off the O_CREATE keyword and instead write:
tie (%car, "SDBM", "car_data", O_RDONLY, 0)
By and large, the fact that we're tieing to an SDBM database
rather than, say, ODBM or GDBM is relatively transparent to us. Once
the hash is tied, we proceed as usual in handling the hash. The
exception to this is when the DBM provides features beyond the basic
Perl hash. Let's consider two examples of this: DB_File's BTree hash,
and MLDBM's support for multi-level hash structures.
A Fistful of DBM's
The Perl You Need to Know
Climbing the BTree
|