15

我已经编写了以下 perl 脚本,但问题是它总是在 else 部分并且报告不是文件。我在输入的目录中确实有文件。我在这里做错了什么?

我的要求是递归访问目录中的每个文件,打开它并以字符串形式读取它。但是逻辑的第一部分是失败的。

#!/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";
    }
}
4

1 回答 1

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";
    }
}
于 2011-03-09T07:50:22.340 回答