use DB_File;
Tie a hash to a DBM-style file:
tie(%hash, "DB_File", $filename) # Open database. or die "Can't open $filename: $!"; $v = $hash{"key"}; # Retrieve from database. $hash{"key"} = "value"; # Put value into database. untie %hash;
Tie a hash to a B-tree file, but still access as a regular DBM hash:
tie(%hash, "DB_File", "mytree", O_RDWR|O_CREAT, 0666, $DB_BTREE) or die "Cannot open file `mytree': $!"; while (($k, $v) = each %hash) { # Do in-order traversal. print "$k => $v "; }
Tie an array to a plain text file:
tie(@lines, "DB_File", $textfile, O_RDWR|O_CREAT, 0666, $DB_RECNO) or die "Cannot open textfile $textfile: $!"; # Write a few lines to the file, overwriting any old contents. $lines[0] = "first line"; $lines[1] = "second line"; $lines[2] = "third line"; push @lines, "penult", "last"; # Append two lines to the file. $wc = scalar @lines; # Count lines in file. $last = pop @lines; # Delete and retrieve last line.
The DB_File
module provides tied access to
Berkeley DB.[1] The default tie
function gives you a
standard DBM-style database with some features that no other DBM
library provides: there are no size limits on either keys or values,
and your data is stored in a byte-order independent format.
The second tie
mechanism uses B-trees to give
you a true ISAM (indexed sequential access method) file, that is, a
hash whose keys are automatically ordered—alphabetically by default,
but configurable by the user.
The third tie
mechanism binds an array to a
file of records (text lines by default) so that changes to the array
are automatically reflected on disk. This simulates random access by
line number on a regular text file. The standard interface conforms to
version 1.x of Berkeley DB; if you want to make use of
the new features available in Berkeley DB 2.x or 3.x, use the CPAN
module BerkeleyDB
instead.
Starting with version 2.x, Berkeley DB has internal support for
locking; earlier versions did not. See Section 16.2.1 in Chapter 16 for a description of how you
can safely lock any kind of database file using
flock
on a semaphore file.
[1] Providing you have that library installed on your system. If not, you can build and install it easily enough.