Perl脚本:递归列出目录中所有文件名

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

这段代码在我的电脑上(ActiveState Perl 5.10 on XP)运行得非常好。你是怎么调用你的脚本的?你所说的“但逻辑的第一部分失败了”具体指什么? - DVK
你使用的是哪个平台?Perl 版本是多少? - weismat
我的要求是递归访问目录中的每个文件,打开它并将其读入字符串。但是逻辑的第一部分失败了。我指的是访问目录中的每个文件。对于我来说,文件检查失败了。 - TopCoder
1
@TopCoder:这是which的版本,你只需要perl --version或者perl -V,或者如果perl不在你的PATH中,也许是$(which perl) --version或者$(which perl) -V - mu is too short
我在这里做错了什么? - TopCoder
显示剩余2条评论
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";
    }
}

我的错误!删除了虚假评论并点赞。 - FMc

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接