【问题标题】:Storing specific fields from multiple files into an array将多个文件中的特定字段存储到数组中
【发布时间】:2016-02-03 14:44:44
【问题描述】:

将多个文件存储到我通常使用的数组中:

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

效果很好。

但是,如果我不想推送整个 $_ 而只存储特定字段,我该怎么办?

我尝试拆分 $_ 并推送特定字段,例如$F[2] 以及拆分 $_ 并重新加入其中的特定元素并推送结果:

@files = glob("*.txt");
my @ID;
for my $file(@files) {
   open IN, '<', $file or die "$!";
   my @F = split(' ', $_);
   $fields = join "\t", @F[0,1,2,3];
   push @ID, $fields while (<IN>);
}

但是,当使用第二个代码块时,@ID 是空的。

【问题讨论】:

    标签: perl


    【解决方案1】:

    您试图在设置 $_ 之前拆分 $_。您需要将该代码移动到 while 循环中:

    @files = glob("*.txt");
    my @ID;
    for my $file(@files) {
       open IN, '<', $file or die "$!";
       while (<IN>) {
          my @F = split(' ', $_);
          $fields = join "\t", @F[0,1,2,3];
          push @ID, $fields;
       }
    }
    

    【讨论】:

    • split ( ' ', $_)split; 的默认大小写(尽管请不要使用单字母变量名)
    【解决方案2】:

    它不是空的。

    $VAR1 = [
              "\t\t\t",
              "\t\t\t",
              ...
              "\t\t\t"
            ];
    

    但它也不包含你想要的。

    您试图拆分您读取的每一行,但您甚至在从文件中读取之前就这样做了!修复:

    while (<IN>) {
       my @F = split(' ', $_);
       my $fields = join "\t", @F[0,1,2,3];
       push @ID, $fields;
    }
    

    总是使用use strict; use warnings qw( all );!这会发现你的问题。

    Use of uninitialized value $_ in split at a.pl line 7.
    

    【讨论】:

      【解决方案3】:

      那些代码片段这样写的比较整齐

      my @ID;
      
      for my $file ( glob '*.txt' ) {
          open my $fh, '<', $file or die $!;
          push @ID, <$fh>;
      }
      

      my @ID;
      
      for my $file ( glob '*.txt' ) {
          open my $fh, '<', $file or die $!;
          push @ID, join "\t", (split)[0 .. 3] while <$fh>;
      }
      

      请注意,我使用了 lexical 文件句柄,当它们超出范围时将隐式关闭,因此无需编写显式 close

      在前一种情况下,每个数组元素仍然附加一个换行符,可能需要使用chomp @ID 删除

      在后一种情况下,最好将每个字段列表存储为一个数组,而不是将它们组合成一个字符串,稍后可能需要再次拆分该字符串以单独访问这些字段。看起来像

      push @ID, [ (split)[0..3] ] while <$fh>;
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-07-10
        • 1970-01-01
        • 2015-10-03
        • 2016-02-23
        • 1970-01-01
        • 1970-01-01
        • 2013-02-21
        • 1970-01-01
        相关资源
        最近更新 更多