Perl Cookbook

Perl CookbookSearch this book
Previous: 14.1. Making and Using a DBM FileChapter 14
Database Access
Next: 14.3. Converting Between DBM Files
 

14.2. Emptying a DBM File

Problem

You want to clear out a DBM file.

Solution

Open the database and assign () to it. Use dbmopen:

dbmopen(%HASH, $FILENAME, 0666)         or die "Can't open FILENAME: $!\n";
%HASH = ();
dbmclose %HASH;

or tie:

use DB_File;

tie(%HASH, "DB_File", $FILENAME)        or die "Can't open FILENAME: $!\n";
%HASH = ();
untie %hash;

Alternatively, delete the file and reopen with create mode:

unlink $FILENAME
    or die "Couldn't unlink $FILENAME to empty the database: $!\n";
dbmopen(%HASH, $FILENAME, 0666)
    or die "Couldn't create $FILENAME database: $!\n";

Discussion

It may be quicker to delete the file and create a new one than to reset it, but doing so opens you up to a race condition that trips up a careless program or makes it vulnerable to an attacker. The attacker could make a link pointing to the file /etc/precious with the same name as your file between the time when you deleted the file and when you recreated it. When the DBM library opens the file, it clobbers /etc/precious.

If you delete a DB_File database and recreate it, you'll lose any customizable settings like page size, fill-factor, and so on. This is another good reason to assign the empty list to the tied hash.

See Also

The documentation for the standard DB_File module, also in Chapter 7 of Programming Perl; the unlink function in perlfunc (1); Recipe 14.1


Previous: 14.1. Making and Using a DBM FilePerl CookbookNext: 14.3. Converting Between DBM Files
14.1. Making and Using a DBM FileBook Index14.3. Converting Between DBM Files

Library Navigation Links

Copyright © 2001 O'Reilly & Associates. All rights reserved.