如何有效地清空 Perl DBM 文件?

发布于 2024-07-06 09:52:48 字数 234 浏览 6 评论 0原文

我继承了一段代码,其中包含一个清空数据库的代码片段,如下所示:

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

这通常没问题,但有时在调用此清理代码之前数据库会变得非常大,并且通常是在用户想要执行重要操作时。

有更好的方法吗?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

离旧人 2024-07-13 09:52:49

这里还有另一个答案,由于某种原因消失了,但它可能会更快,所以我重新发布它(不知道为什么它被删除)。 它涉及取消文件链接以将其删除,然后重新创建一个空白数据库文件,如下所示:

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

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);
jJeQQOZ5 2024-07-13 09:52:48

您可以删除该文件:

unlink $file;

由于 dbmopen 的第三个参数是文件模式,不是 undefdbmopen 将在下次调用时重新创建该文件:

dbmopen my %db, $file, 0666;

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;
你对谁都笑 2024-07-13 09:52:48

事实上,一位同事给我指出了一个解决方案。 您显然可以这样做:

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

在关闭数据库之前清除散列。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文