gpt4 book ai didi

perl - 为什么我不能在 Perl 中删除这个空目录?

转载 作者:行者123 更新时间:2023-12-03 18:08:47 25 4
gpt4 key购买 nike

我正在从 http://www.perlmonks.org/index.pl?node_id=217166 转换一个 linux 脚本特别是这个:

#!/usr/bin/perl -w
use strict;
use Getopt::Std;
use File::Find;

@ARGV > 0 and getopts('a:', \my %opt) or die << "USAGE";
# Deletes any old files from the directory tree(s) given and
# removes empty directories en passant.
usage: $0 [-a maxage] directory [directory ...]
-a maximum age in days, default is 120
USAGE

my $max_age_days = $opt{a} || 120;

find({
wanted => sub { unlink if -f $_ and -M _ > $max_age_days },
postprocess => sub { rmdir $File::Find::dir },
}, @ARGV);

我的尝试是:
#!/usr/bin/perl -w
use strict;
use Getopt::Std;
use File::Find;


@ARGV > 0 and getopts('a:', \my %opt) or die << "USAGE";
# Deletes any old files from the directory tree(s) given and
# removes empty directories en passant.
usage: $0 [-a maxage] directory [directory ...]
-a maximum age in days, default is 120
USAGE

my $max_age_days = $opt{a} || 120;

find({
wanted => sub { unlink if -f $_ and -M _ > $max_age_days },
# postprocess => sub { rmdir $File::Find::dir },
postprocess => sub {
my $expr = "$File::Find::dir";
$expr =~ s/\//\\/g; # replace / with \
print "rmdir $expr\n";
`rmdir $expr`;
},
}, @ARGV);

但是,当脚本尝试删除一个目录时,我收到一个错误,说明该目录正在被另一个进程使用(如果不是)。有任何想法吗?我正在使用 ActiveState 5.10 在 Windows Server 2003 SP2 64 位上运行该脚本。

谢谢!

最佳答案

从这里 documentation

postprocess

The value should be a code reference. It is invoked just before leaving the currently processed directory. It is called in void context with no arguments. The name of the current directory is in $File::Find::dir. This hook is handy for summarizing a directory, such as calculating its disk usage. When follow or follow_fast are in effect, postprocess is a no-op.



这意味着当您尝试删除该目录时,您自己的代码仍在使用该目录。尝试构建一个名称列表并在调用 find 后遍历该列表。

另一种可能的解决方案是使用 no_chdir避免让 find 使用要删除的目录的选项。

编辑:此评论也相关,因此我将其推广到主要答案的正文:

To add to that: the issue here is that on Linux one can delete files and directories that are in use, on windows one can't. That's why it doesn't work unmodified. - Leon Timmermans

关于perl - 为什么我不能在 Perl 中删除这个空目录?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/349953/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com