perl脚本以递归方式列出目录中的所有文件名 [英] perl script to recursively list all filename in directory
问题描述
我写了以下perl脚本,但问题是它总是出现在其他部分,而不报告文件.我确实在输入中提供的目录中有文件.我在这里做什么错了?
I have written following perl script but problem is its always going in else part and reporting not a file. I do have files in the directory which I am giving in input. What am I doing wrong here?
我的要求是递归访问目录中的每个文件,将其打开并以字符串形式读取.但是逻辑的第一部分失败了.
My requirement is to recursively visit every file in a directory, open it and read it in a string. But the first part of the logic is failing.
#!/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";
}
}
推荐答案
$File::Find::name
给出相对于原始工作目录的路径.但是,除非另有说明,否则 File :: Find 会不断更改当前工作目录.
$File::Find::name
gives the path relative to original working directory. However, File::Find keeps changing the current working directory unless you tell it otherwise.
要么使用no_chdir
选项,要么使用仅包含文件名部分的-f $_
.我推荐前者.
Either use the no_chdir
option, or use -f $_
which contains just the file name portion. I recommend the former.
#!/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";
}
}
这篇关于perl脚本以递归方式列出目录中的所有文件名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!