我正在尝试使用File :: Find来查找1)通过给定的文件夹和子文件夹,删除任何超过30天的文件,以及b)如果在删除所有删除后父文件夹为空,也删除它。perl File :: Find - 删除某些条件下的文件,然后删除父文件夹如果为空
这里是我的代码:
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:/杰森/温度/测试/ OEBPS /媒体/被删除,但删除没有被预处理FUNC被称为时间登记。任何想法如何让这个工作?谢谢!
感谢, BP
一个,你不[取消链接](http://perldoc.perl.org/functions/unlink.html)目录,使用[命令rmdir(http://perldoc.perl.org/functions/ rmdir.html) – Miller
您不检查是否可以创建输出LOG。另外,关闭警告通常是一个坏主意。未初始化的变量是最有用的单个警告,并且您已将其关闭。它在那里帮助你。 –