2014-11-24 67 views
0

我有两个制表符分隔表:比较不同表的值perl的

table1 

col1 col2 col3 col4 
id1  1  1  10 
id2  1  15  20 
id3  1  30  35 
id4  2  10  15 


table2 

col1 col2 col3 
rs1  5  1 
rs2  11  1 
rs3  34  1 
rs4  35  1 

我首先要检查是否有在COL3,表2和COL2-table1的值之间的匹配。如果这是TRUE,那么我想检查col2-table2中的值是否在col3 & col4 - table1中的值之间。如果是这种情况,我想将col1的相应值(col)打印到col1的新列中。

所以在这个例子中,最终的结果文件应该是这样的:

table output 
col1 col2 col3 col4 new_col1  
id1  1  1  10  rs1:5 
id2  1  15  20  
id3  1  30  35  rs3:34, rs4:35  
id4  2  10  15 

开幕后和加载文件时,我开始与存储数组的数组表2的值。

my @table2; 
    while (<$table2>){ 
     next if /^\s*#/; #to skip header lines 
     my @columns = split; 
     next if $columns[1] =~ /\D/; 
     push @table2, \@columns; 
     } 

while (<$table1>){ 
    my @columns = split; 
    ... 
} 

我怎么能现在检查是否有在COL3,表2的价值和COL2-table1的之间的匹配。然后如何继续检查col2-table2中的值是否在col3 & col4 - table1中的值之间。

+1

请阅读的perldoc perldsc和perllol的 – Vorsprung 2014-11-24 08:50:08

+1

可能重复的[找到的值的范围内的2个值的](http://stackoverflow.com/questions/27063288 /发现值-IN-A-范围为2的值) – Sobrique 2014-11-24 09:39:19

回答

1

幸运的是,我上次在我的记事本中仍然有代码。

我根据更改的要求进行了几项更新。这应该做你所要求的。 (在没有内联的情况下提供表格数据作为读者的练习)。

use strict; 
use warnings; 
use Data::Dumper; 

my %table2; 

while (<DATA>) { 

    #stop reading if we've finished with table2 
    last if m/^table1/; 

    next unless m/^rs/; 
    my ($col1, $col2, $col3) = split(/\s+/); 
    $table2{$col1}{$col3} = $col2; 
} 

print "The story so far...:\n"; 
print Dumper \%table2; 


print "table output\n"; 
print join("\t", qw (col1 col2 col3 col4 new_col1)), "\n"; 
while (<DATA>) { 
    next unless m/^id/; 
    chomp; 
    my ($rowid, $col2, $lower, $upper) = split(/\s+/); 
    my $newcol = ""; 
    foreach my $rs (keys %table2) { 
     if (defined $table2{$rs}{$col2} 
      and $table2{$rs}{$col2} >= $lower 
      and $table2{$rs}{$col2} <= $upper) 
     { 
      $newcol .= " $rs:$table2{$rs}{$col2}"; 
     } 
    } 
    print join("\t", $rowid, $col2, $lower, $upper, $newcol,), "\n"; 
} 


__DATA__ 
table2 
col1 col2 col3 
rs1  5  1 
rs2  11  1 
rs3  34  1 
rs4  35  1 

table1 
col1 col2 col3 col4 
id1  1  1  10 
id2  1  15  20 
id3  1  30  35 
id4  2  10  15 

这给出的输出:

The story so far...: 
$VAR1 = { 
      'rs3' => { 
        '1' => '34' 
        }, 
      'rs4' => { 
        '1' => '35' 
        }, 
      'rs2' => { 
        '1' => '11' 
        }, 
      'rs1' => { 
        '1' => '5' 
        } 
     }; 

table output 
col1 col2 col3 col4  new_col1 
id1  1  1  10  rs1:5 
id2  1  15  20 
id3  1  30  35  rs3:34 rs4:35 
id4  2  10  15