|
Working with DBM Files
Part:
1
2
This chapter describes:
- How bind a DBM file to a hash object.
- Sample programs to use DBM files.
Opening DBM Files with Hash Objects
Perl allows us to access DBM files by binding them to hash objects. There are two
related functions:
1. dbmopen() - A function to bind the specified hash variable to the specified
DBM file. The specified mask value will be used as the permission code,
if the specified DBM file does not exist. Of course, previously existing entries
of the hash variable will be removed at the time of binding.
rc = dbmopen(hash_variable, dbm_name, mask);
2. dbmclose() - A function to un-bind the specified hash variable from the binded
DBM file.
rc = dbmclose(hash_variable);
DBM Example - English French Dictionary
As the first example with DBM files, I wrote several simple programs to create
a simple English French dictionary, to update the dictionary, and to look up word
in the dictionary.
The first program, DbmInsert.pl, creates the dictionary as a DBM file, and inserts a couple
of entries:
#- DbmInsert.pl
#- Copyright (c) 1996 by Dr. Herong Yang
#
($name) = @ARGV;
die "Missing DBM name.\n" unless $name;
dbmopen(%map,$name,0666);
$map{'apple'} = 'pomme';
$map{'bible'} = 'bible';
$map{'cloth'} = 'tissu';
$map{'computer'} = 'ordinateur';
$map{'good'} = 'bon';
$map{'milk'} = 'lait';
$map{'price'} = 'prix';
$map{'ten'} = 'dix';
dbmclose(%map);
exit;
The mask code, 0666, is an octal number representing a permission setting
to allow every user for reading and writing (rw_rw_rw_). Running this program
gives no problem:
>DbmInsert.pl dictionary
>dir dictionary.*
0 dictionary.dir
1,024 dictionary.pag
The second program, DbmPrint.pl, prints the entire content of the dictionary:
#- DbmPrint.pl
#- Copyright (c) 1996 by Dr. Herong Yang
#
($name) = @ARGV;
die "Missing DBM name.\n" unless $name;
dbmopen(%map,$name,0666);
while (($key,$val)=each(%map)) {
print($key, ' = ', $val, "\n");
}
dbmclose(%map);
exit;
No trouble to run this program. Notice that the order of the entries is maintained
as the same as they were inserted by the first program:
>DbmPrint.pl dictionary
apple = pomme
bible = bible
cloth = tissu
computer = ordinateur
good = bon
milk = lait
price = prix
ten = dix
The third program, DbmUpdate.pl, deletes an entry, and updates another entry:
#- DbmUpdate.pl
#- Copyright (c) 1996 by Dr. Herong Yang
#
($name) = @ARGV;
die "Missing DBM name.\n" unless $name;
dbmopen(%map,$name,0666);
delete($map{'apple'});
$map{'cloth'} = 'vetement';
dbmclose(%map);
exit;
(Continued on next part...)
Part:
1
2
|