无论我用于TARGET的目录是什么,这个Perl代码都正确地找到了TARGET中每个子目录和文件的名称,但随后确定除了“。”之外它们都不存在。和“..”。
my $source_dir = "C:\\path to directory\\TARGET;
opendir(my $DIR, $source_dir) || die $!;
while (my $file = readdir($DIR))
{
my $file_exists = (-e $file ? "exists" : "does not exist");
print("$file $file_exists\n");
}
输出:
. exists
.. exists
FILE does not exist # where FILE is the name of every other subdirectory or file in TARGET
真正令我感到困惑的是,如果我将TARGET更改为其中一个子目录,则脚本会成功导航到子目录 - 之前已确定它不存在 - 然后在新子目录中生成相同的输出。 / p>
感谢任何建议。
答案 0 :(得分:3)
readdir
仅返回文件名,而不是整个路径。因此,-e $file
会在当前工作目录中查找$file
,而不是$source_dir
。每个目录都包含名为.
和..
的条目,因此可以找到这些条目。但是,工作目录中的其他文件都没有$source_dir
中的文件同名,所以当-e
寻找它们时找不到它们。
因此,您需要合并$source_dir
和$file
:
use File::Spec::Functions qw/catfile/;
my $full_path = catfile($source_dir, $file);
my $file_exists = (-e $full_path ? "exists" : "does not exist");
print("$file $file_exists\n");
答案 1 :(得分:2)
您还可以使用一些模块,这些模块允许您使用许多额外的缓动功能,我最喜欢的是Path::Tiny。 E.g:
use 5.010;
use warnings;
use Path::Tiny;
$iter = path("C://Users/jm")->iterator;
while ( $path = $iter->() ) {
say "$path";
}
迭代器会自动跳过.
和..
,您可以添加选项以递归到子目录等等......