【问题标题】:perl script to recursively list all filename in directoryperl脚本递归列出目录中的所有文件名
【发布时间】:2011-07-11 15:10:37
【问题描述】:

我已经编写了以下 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";
    }
}

【问题讨论】:

  • 这段代码对我来说似乎工作得很好(XP 上的 ActiveState Perl 5.10)。你怎么称呼你的脚本? “但是逻辑的第一部分失败了。”究竟是什么意思?
  • 您使用的是哪个平台?哪个 perl 版本?
  • “我的要求是递归访问目录中的每个文件,打开它并以字符串的形式读取它。但是逻辑的第一部分失败了。”我的意思是逻辑的第一部分,访问目录中的每个文件。我的文件检查失败。
  • @TopCoder: 那是which 的版本,你只需要perl --versionperl -V,或者$(which perl) --version$(which perl) -V 如果perl 不在你的PATH 中.
  • 抱歉,这是正确的版本:perl, v5.8.8 built for x86_64-linux-thread-multi

标签: perl file file-find


【解决方案1】:

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

【讨论】:

  • 我的错!删除虚假评论和 +1。
猜你喜欢
  • 1970-01-01
  • 2011-10-20
  • 2010-10-19
  • 1970-01-01
  • 2021-12-18
  • 2010-10-04
  • 2010-10-30
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多