#!/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:',# 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位上运行该脚本.
谢谢!
解决方法
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选项以避免找到使用您要删除的目录.
编辑:此评论也是相关的,所以我将它推广到主答案的正文:
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. – 07001