【问题标题】:add multiples files to an array in perl在perl中将多个文件添加到数组中
【发布时间】:2017-07-17 18:36:20
【问题描述】:

我有一些包含大量行列表的 txt 文件,例如:

file_1.txt        file_2.txt      file_3.txt
XP_001703830.1    XP_001703820.1  XP_001703810.1
XP_001703836.1    XP_001703815.1  XP_001703805.1
XP_001703844.1    XP_001703834.1  XP_001703844.1

假设我在一个文件夹中有 10 个或更多文件,我想读取所有文件并将内容存储在一个数组中,我使用过这段代码,但它只存储文件的一行,而不是所有的线条!

#!/usr/bin/perl -w
use strict;

my @files = glob("*.txt");
my @ID;

for my $file(@files) {
    open IN, '<', $file or die "$!";
        while (<IN>) {
            my $fields = $_;
            push @ID, $fields;
        }
}

foreach (@ID){
    print "$_\n";
}
close IN;
exit;

我想要的是将所有行存储在一个数组中,例如:

XP_001703830.1      
XP_001703836.1      
XP_001703844.1      
XP_001703820.1
XP_001703815.1
XP_001703834.1
XP_001703810.1
XP_001703805.1
XP_001703844.1

非常感谢!!!

【问题讨论】:

  • 第一个close IN; 应该在for 循环下,您正在打开一个txt 文件。
  • 我完全能够使用您的确切代码将所有行存储在一个数组中!你在@ID 得到什么?
  • 你为什么要改造cat

标签: arrays list perl


【解决方案1】:

如果你还是要将整个东西读入内存(通常不是最好的 RAM 使用),那么你可以这样做... perl TIMTOWTDI

my @ID;
{
    local(@ARGV) =  glob("*.txt");
    @ID=<>;
}
print "@ID\n";

【讨论】:

    【解决方案2】:

    通过将默认输入分隔符初始化为undef可以解决这个问题,

    use strict;
    my @files = glob("*.txt");
    my @ID;
    
    for my $file(@files) {
        open IN, '<', $file or die "$!";
        while (<IN>) {
            my $fields = do{local $/; <IN>};
            push @ID, $fields;
        }
    }
    
    foreach (@ID){
        print "$_\n";
    }
    close IN;
    exit;
    

    【讨论】:

      【解决方案3】:

      我猜你的行终止符有问题。试试

      open IN, '<:crlf', $file
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-02-05
        • 2023-04-03
        • 1970-01-01
        • 2017-12-28
        • 2017-07-14
        • 2016-06-14
        相关资源
        最近更新 更多