Making and Using a DBM File
Problem
You want to create, populate, inspect, or delete values in a DBM database.
Solution
Use
dbmopen
or
tie
to open the database and make it accessible
through a hash. Then use the hash as you normally would. When
you’re done, call
dbmclose
or
untie
.
dbmopen
use DB_File; # optional; overrides default dbmopen %HASH, $FILENAME, 0666 # open database, accessed through %HASH or die "Can't open $FILENAME:$!\n"; $V = $HASH{$KEY}; # retrieve from database $HASH{$KEY} = $VALUE; # put value into database if (exists $HASH{$KEY}) { # check whether in database # ... } delete $HASH{$KEY}; # remove from database dbmclose %HASH; # close the database
tie
use DB_File; # load database module tie %HASH, "DB_File", $FILENAME # open database, to be accessed or die "Can't open $FILENAME:$!\n"; # through %HASH $V = $HASH{$KEY}; # retrieve from database $HASH{$KEY} = $VALUE; # put value into database if (exists $HASH{$KEY}) { # check whether in database # ... } delete $HASH{$KEY}; # delete from database untie %HASH; # close the database
Discussion
Accessing a database as a hash is powerful but easy, giving you a persistent hash that sticks around after the program using it has finished running. It’s also much faster than loading in a new hash every time; even if the hash has a million entries, your program starts up virtually instantaneously.
The program in Example 14.1 treats the database as though it were a normal
hash. You can even call keys
or
each
on it. Likewise, exists ...
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.