DB_HASH This database type allows arbitrary key/data pairs to be stored in data files. This is equivalent to the functionality provided by other hashing packages like DBM, NDBM, ODBM, GDBM, and SDBM. Remember though, the files created using DB_HASH are not compatible with any of the other packages mentioned. A default hashing algorithm, which will be adequate for most applications, is built into Berkeley DB. If you do need to use your own hashing algorithm it is possible to write your own in Perl and have DB_File use it instead. DB_BTREE The btree format allows arbitrary key/data pairs to be stored in a sorted, balanced binary tree. As with the DB_HASH format, it is possible to provided a user defined Perl routine to perform the comparison of keys. By default, though, the keys are stored in lexical order. DB_RECNO DB_RECNO allows both fixed-length and variable-length flat text files to be manipulated using the same key/value pair interface as in DB_HASH and DB_BTREE. In this case the key will consist of a record (line) number.
tie %h, "DB_File", "hashed", O_RDWR|O_CREAT, 0640, $DB_HASH ;
# Add a key/value pair to the file
$h{"apple"} = "orange" ;
# Check for existence of a key
print "Exists\n" if $h{"banana"} ;
# Delete
delete $h{"apple"} ;
untie %h ;
use DB_File ; use Fcntl ; sub Compare { my ($key1, $key2) = @_ ; "\L$key1" cmp "\L$key2" ; } $DB_BTREE->{compare} = 'Compare' ; tie %h, 'DB_File', "tree", O_RDWR|O_CREAT, 0640, $DB_BTREE ; # Add a key/value pair to the file $h{'Wall'} = 'Larry' ; $h{'Smith'} = 'John' ; $h{'mouse'} = 'mickey' ; $h{'duck'} = 'donald' ; # Delete delete $h{"duck"} ; # Cycle through the keys printing them in order. # Note it is not necessary to sort the keys as # the btree will have kept them in order automatically. foreach (keys %h) { print "$_\n" } untie %h ;
Example Using DB_RECNO
use DB_File ; use Fcntl ; $DB_RECNO->{psize} = 3000 ; tie @h, DB_File, "text", O_RDWR|O_CREAT, 0640, $DB_RECNO ; # Add a key/value pair to the file $h[0] = "orange" ; # Check for existence of a key print "Exists\n" if $h[1] ; untie @h ;