tags:

views:

452

answers:

3

I've inherited a piece of code with a snippet which empties the database as follows:

dbmopen (%db,"file.db",0666);
foreach $key (keys %db) {
  delete $db{$key};
}
dbmclose (%db);

This is usually okay but sometimes the database grows very large before this cleanup code is called and it's usually when a user wants to do something important.

Is there a better way of doing this?

+6  A: 

Actually, a workmate has pointed me to a solution. You can apparently do:

dbmopen (%db,"file.db",0666);
%db = ();
dbmclose (%db);

which clears out the hash before closing the database.

paxdiablo
+6  A: 

There was another answer here which has disappeared for some reason, yet it was likely to be faster, so I'm reposting it (not sure why it was deleted). It involves unlinking the file to delete it then just recreating a blank database file as follows:

unlink ("file.db");
dbmopen (%db,"file.db",0666);
dbmclose (%db);
paxdiablo
+9  A: 

You can just delete the file:

unlink $file;

Since your third argument to dbmopen is a file mode and not undef, dbmopen will recreate the file the next time it's called:

dbmopen my %db, $file, 0666;
brian d foy