在 Perl 中解析多个文件

kay*_*ato 0 perl parsing

请更正我的代码,我似乎无法打开文件进行解析。错误是这一行open(my $fh, $file) or die "Cannot open file, $!"; 无法打开文件,在 ./sample.pl 第 28 行没有这样的文件或目录。

use strict;
my $dir = $ARGV[0];

my $dp_dpd = $ENV{'DP_DPD'};

my $log_dir = $ENV{'DP_LOG'};
my $xmlFlag = 0;
my @fileList = "";

my @not_proc_dir = `find $dp_dpd -type d -name "NotProcessed"`;

#print "@not_proc_dir\n";


foreach my $dir (@not_proc_dir) {
        chomp ($dir);
        #print "$dir\n";

    opendir (DIR, $dir) or die "Couldn't open directory, $!";
    while ( my $file = readdir DIR) {
            next if $file =~ /^\.\.?$/;
            next if (-d $file);
       #   print "$file\n";
            next if $file eq "." or $file eq "..";
                    if ($file =~ /.xml$/ig) {
                     $xmlFlag = 1;
                     print "$file\n";
                     open(my $fh, $file) or die "Cannot open file, $!";
                    @fileList = <$fh>;
                    close $file;


                    }

            }
            closedir DIR;

}
Run Code Online (Sandbox Code Playgroud)

Dad*_*ada 8

引用readdir文档

如果您打算对 readdir 中的返回值进行文件测试,则最好预先添加有问题的目录。否则,因为我们没有 chdir 在那里,它会测试错误的文件。

open(my $fh, $file)因此你应该是open my $fh, '<', "$dir/$file"(注意我也是如何添加的'<':你应该总是使用 3-argument open)。

next if (-d $file);也错了,应该是next if -d "$dir/$file";


关于您的代码的一些附加说明:

  • 始终添加use warnings到您的脚本中(除了use strict您已经拥有的 )

  • 使用词法文件/目录句柄而不是全局句柄。也就是说,做opendir my $DH, $dir,而不是opendir DH, $dir

  • 正确缩进您的代码(if ($file =~ /.xml$/ig) {太深一层;它使您更难阅读代码)

  • next if $file =~ /^\.\.?$/;并且next if $file eq "." or $file eq "..";是多余的(即使在技术上不是等效的);我建议只使用后者。

  • $dir定义的变量my $dir = $ARGV[0];从未使用过。