我已经编写了以下perl脚本但问题是它总是在其他部分进行并且报告不是文件。我在输入的目录中有文件。我在这里做错了什么?
我的要求是以递归方式访问目录中的每个文件,打开它并以字符串形式读取它。但逻辑的第一部分是失败的。
#!/usr/bin/perl -w
use strict;
use warnings;
use File::Find;
my (@dir) = @ARGV;
find(\&process_file,@dir);
sub process_file {
#print $File::Find::name."\n";
my $filename = $File::Find::name;
if( -f $filename) {
print " This is a file :$filename \n";
} else {
print " This is not file :$filename \n";
}
}
答案 0 :(得分:19)
$File::Find::name
给出了相对于原始工作目录的路径。但是,File::Find会不断更改当前工作目录,除非您另有说明。
使用no_chdir
选项,或使用仅包含文件名部分的-f $_
。我推荐前者。
#!/usr/bin/perl -w
use strict;
use warnings;
use File::Find;
find({ wanted => \&process_file, no_chdir => 1 }, @ARGV);
sub process_file {
if (-f $_) {
print "This is a file: $_\n";
} else {
print "This is not file: $_\n";
}
}