【问题标题】:How can I extract specific columns in perl?如何在 perl 中提取特定列?
【发布时间】:2017-07-12 22:13:31
【问题描述】:
chr1    1   10  el1
chr1    13  20  el2
chr1    50  55  el3

我有这个制表符分隔的文件,我想使用 perl 提取第二列和第三列。我该怎么做?

我尝试使用文件处理程序读取文件并将其存储在字符串中,然后将字符串转换为数组,但它没有让我到任何地方。

我的尝试是:

while (defined($line=<FILE_HANDLE>)) {
    my @tf1;
    @tf1 = split(/\t/ , $line);
}

【问题讨论】:

  • 那是您在脚本中编写的代码吗? while 代码块周围缺少大括号,如果您输入“use strict;”,则会产生错误。在脚本的顶部
  • 我的整个代码超过 100 行,它包含使用严格和使用警告。这只是摘录
  • 原样的代码(带有大括号)应该做你想做的事——所以问题很可能出在其他地方。 minimal reproducible example 会告诉我们问题出在哪里
  • 你的代码真的有那么糟糕吗?我不明白为什么人们不花更多的精力来格式化他们的代码。
  • 我已经修复了您的代码格式。不客气,但请以后自己做。当您要求陌生人阅读和理解您的代码时,尽可能让其易于理解是礼貌的做法。

标签: perl


【解决方案1】:

在标签上简单地自动拆分

#                                      ↓ index starts on 0
$ perl -F'\t' -lane'print join ",", @F[1,2]' inputfile

输出:

1,10
13,20
50,55

perlrun

【讨论】:

    【解决方案2】:
    use strict;
    
    my $input=shift or die "must provide <input_file> as an argument\n";
    
    open(my $in,"<",$input) or die "Cannot open $input for reading: $!";
    
    while(<$in>)
    {
        my @tf1=split(/\t/,$_);
        print "$tf1[1]|$tf1[2]\n"; # $tf1[1] is the second column and $tf1[2] is the third column
    }
    close($in)
    

    【讨论】:

      【解决方案3】:

      你有什么问题?您的代码已经完成了所有困难的部分。

      while (defined($line=<FILE_HANDLE>)) {
          my @tf1;
          @tf1 = split(/\t/ , $line);
      }
      

      您的@tf1 数组中有所有三列(顺便说一下 - 您的变量命名需要认真工作!)您现在需要做的就是打印数组中的第二个和第三个元素(但请记住 Perl 数组元素从零开始编号)。

      print "$tf1[1] / $tf1[2]\n";
      

      利用 Perl 的默认行为可以大大简化您的代码。

      while (<FILE_HANDLE>) {          # Store record in $_
          my @tf1 = split(/\t/);       # Declare and initialise on one line
                                       # split() works on $_ by default
          print "$tf1[1] / $tf1[2]\n";
      }
      

      【讨论】:

        【解决方案4】:

        比@daxim 更简洁:

        perl -aE 'say "@F[1,2]" ' file
        

        另请参阅:How to sort an array or table by column in perl?

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2023-04-10
          • 1970-01-01
          • 2011-04-12
          • 2012-03-06
          • 2011-10-28
          • 1970-01-01
          相关资源
          最近更新 更多