我正在尝试使用 File::Find 来 1) 遍历给定的文件夹和子文件夹,删除任何超过 30 天的文件,以及 b) 如果父文件夹在所有删除后为空,也将其删除。
这是我的代码:
use strict;
use warnings;
no warnings 'uninitialized';
use File::Find;
use File::Basename;
use File::Spec::Functions;
# excluding some home brew imports
# go into given folder, delete anything older than 30 days, and if folder is then empty, delete it
my $testdir = 'C:/jason/temp/test';
$testdir =~ s#\\#/#g;
open(LOG, ">c:/jason/temp/delete.log");
finddepth({ wanted => \&myWanted, postprocess => \&cleanupDir }, $testdir);
sub myWanted {
if ($_ !~ m/\.pdf$/i &&
int(-M $_) > 30
)
{
my $age = int(-M $_);
my $path = $File::Find::name;
print LOG "age : $age days - $path\n";
unlink($path);
}
}
sub cleanupDir {
my $path = $File::Find::dir;
if ( &folderIsEmpty($path) ) {
print LOG "deleting : $path\n";
unlink($path);
} else {
print LOG "$path not empty\n";
my @files = glob("$path/*");
foreach my $file(@files){
print LOG "\t$file\n";
}
}
}
我原以为 finddepth() 会走到树的底部并向上工作,但那没有发生。该脚本在某些电子书内容的解压缩上运行,即使所有文件都已删除,也不会删除具有子文件夹的目录。
age : 54 days - C:/jason/temp/test/mimetype
age : 54 days - C:/jason/temp/test/META-INF/container.xml
age : 54 days - C:/jason/temp/test/META-INF/ncx.xml.kindle
deleting : C:/jason/temp/test/META-INF
age : 54 days - C:/jason/temp/test/OEBPS/content.opf
age : 54 days - C:/jason/temp/test/OEBPS/cover.html
age : 54 days - C:/jason/temp/test/OEBPS/ncx.xml
age : 54 days - C:/jason/temp/test/OEBPS/pagemap.xml
age : 54 days - C:/jason/temp/test/OEBPS/t01_00_text.html
age : 54 days - C:/jason/temp/test/OEBPS/t02_00_text.html
age : 54 days - C:/jason/temp/test/OEBPS/t03_00_text.html
age : 54 days - C:/jason/temp/test/OEBPS/t04_00_text.html
age : 54 days - C:/jason/temp/test/OEBPS/t05_00_text.html
age : 54 days - C:/jason/temp/test/OEBPS/t06_00_text.html
age : 54 days - C:/jason/temp/test/OEBPS/t07_00_text.html
age : 54 days - C:/jason/temp/test/OEBPS/t08_00_text.html
age : 54 days - C:/jason/temp/test/OEBPS/t08_01_text.html
age : 54 days - C:/jason/temp/test/OEBPS/media/cover.jpg
age : 54 days - C:/jason/temp/test/OEBPS/media/flamlogo.gif
age : 54 days - C:/jason/temp/test/OEBPS/media/logolnmb.jpg
age : 54 days - C:/jason/temp/test/OEBPS/media/stylesheet.css
deleting : C:/jason/temp/test/OEBPS/media
C:/jason/temp/test/OEBPS not empty
C:/jason/temp/test/OEBPS/media
C:/jason/temp/test not empty
C:/jason/temp/test/META-INF
C:/jason/temp/test/OEBPS
看起来 C:/jason/temp/test/OEBPS/media/ 已删除,但在调用预处理函数时未注册该删除。关于如何让它发挥作用的任何想法?谢谢!
谢谢,bp