perl: 无法在循环中打开文件

perl: canot open file within a loop

我正在尝试读入一堆相似的文件并一个一个地处理它们。这是我的代码。但不知何故,perl 脚本无法正确读取文件。我不确定如何解决它。这些文件对我来说绝对是可读可写的。

#!/usr/bin/perl
use strict;
use warnings;

my @olap_f = `ls /full_dir_to_file/*txt`;

foreach my $file (@olap_f){
    my %traits_h;

    open(IN,'<',$file) || die "cannot open $file";

    while(<IN>){
        chomp;
        my @array = split /\t/;
        my $trait = $array[4];
        $traits_h{$trait} ++;
    }
    close IN;

}  

当我 运行 它时,出现错误消息(如下所示):

cannot open /full_dir_to_file/a.txt

每个文件名的末尾都有换行符:

my @olap_f = `ls ~dir_to_file/*txt`;
chomp @olap_f; # Remove newlines

更好的是,使用 glob 避免启动新进程(并且必须 trim 换行符):

my @olap_f = glob "~dir_to_file/*txt";

另外,使用$!找出文件无法打开的原因:

open(IN,'<',$file) || die "cannot open $file: $!";

这会告诉你

cannot open /full_dir_to_file/a.txt
: No such file or directory

这可能会让您识别出不需要的换行符。

我将在此处为 IO::All 添加一个快速插件。了解幕后发生的事情很重要,但有时这样做也很方便:

use IO::All;
my @olap_f = io->dir('/full_dir_to_file/')->glob('*txt');

在这种情况下,它并不比@cjm 使用的 glob 短,但 IO::All 也有一些其他方便的文件处理方法。