DB_File
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\n"; }
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 ...
Get Programming Perl, 3rd Edition 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.