perl 脚本递归列出目录中的所有文件名

问题描述 投票:0回答:2

我已经编写了以下 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";
    }
}
perl file file-find
2个回答
27
投票

$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";
    }
}

0
投票

这是我的答案,读取文件夹和子文件夹中的所有文件并将该内容捕获到文件中

创建一个名为 Amazing_perl.pl 的 Perl 脚本并将其添加到其中

然后像这样运行> perl.exe Amazing_perl.pl c: emp

#!/usr/bin/perl
use strict;
use warnings;
use File::Find qw(finddepth);

my ($TOP_LEVEL_DIR) = @ARGV;

print "Perl Starting ...\n\n";

#create output file
open(my $output_file_handle, '>', "ALL_FILES_AND_FOLDERS.txt");


print "Processing ...\n";
finddepth(sub {
    return if($_ eq '.' || $_ eq '..');
      
    print "Processing ... $_ \n";
  
    my $filePath = $File::Find::name;
    #print "filePath ... $filePath \n";

    print $output_file_handle "$filePath\n";    
      
 }, "$TOP_LEVEL_DIR");

 
print "\n\nPerl End ...\n\n";

sub trim {
(my $s = $_[0]) =~ s/^\s+|\s+$//g;
return $s;
}
1
;
© www.soinside.com 2019 - 2024. All rights reserved.