【发布时间】:2010-12-13 12:23:56
【问题描述】:
我正在努力寻找一种遍历目录树以检查多个目录中是否存在文件的方法。我正在使用 Perl,我只能使用 File::Find,因为我无法为此安装任何其他模块。
这是我要遍历的文件系统的布局:
汽车/本田/思域/Setup/config.txt 汽车/本田/探路者/Setup/config.txt 汽车/丰田/卡罗拉/Setup/config.txt 汽车/丰田/Avalon/Setup/请注意,最后一个安装文件夹缺少config.txt 文件。
编辑:此外,在每个安装文件夹中还有许多其他文件,这些文件因安装文件夹而异。确实没有任何单个文件可供搜索以进入 Setup 文件夹本身。
因此,您可以看到文件路径保持不变,除了 make 和 model 文件夹。我想找到所有的 Setup 文件夹,然后检查该文件夹中是否有 config.txt 文件。
一开始我用File::Find下面的代码
my $dir = '/test/Cars/';
find(\&find_config, $dir);
sub find_config {
# find all Setup folders from the given top level dir
if ($File::Find::dir =~ m/Setup/) {
# create the file path of config.txt whether it exists or not, well check in the next line
$config_filepath = $File::Find::dir . "/config.txt";
# check existence of file; further processing
...
}
}
您可以明显看到尝试使用$File::Find::dir =~ m/Setup/ 时的缺陷,因为它会为Setup 文件夹中的每个文件返回一个命中。有没有办法使用-d 或某种目录检查而不是文件检查? config.txt 并不总是在文件夹中(如果它不存在,我将需要创建它)所以我不能真正使用像 return unless ($_ =~ m/config\.txt/) 这样的东西,因为我不知道它是否存在。
我正在尝试找到一种方法来使用 return unless ( <is a directory> and <the directory has a regex match of m/Setup/>) 之类的东西。
也许File::Find 不是解决此类问题的正确方法,但我已经搜索了一段时间,但在使用目录名而不是文件名方面没有任何好的线索。
【问题讨论】:
-
为什么不能安装其他模块?
-
我犹豫要不要使用任何其他模块,因为要获得批准在生产机器上使用它们的过程很长。