Skip to Content
Programming Perl, 3rd Edition
book

Programming Perl, 3rd Edition

by Larry Wall, Tom Christiansen, Jon Orwant
July 2000
Intermediate to advanced
1104 pages
35h 1m
English
O'Reilly Media, Inc.
Content preview from Programming Perl, 3rd Edition

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 ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Programming Perl, 4th Edition

Programming Perl, 4th Edition

Tom Christiansen, brian d foy, Larry Wall, Jon Orwant
Learning Perl, 7th Edition

Learning Perl, 7th Edition

Randal L. Schwartz, brian d foy, Tom Phoenix
Programming the Perl DBI

Programming the Perl DBI

Tim Bunce, Alligator Descartes

Publisher Resources

ISBN: 0596000278Supplemental ContentErrata