2017-03-08 120 views
0

我对编码相当缺乏经验,但我经常使用Perl合并文件并在两个文件之间匹配ID和信息。我刚刚尝试过使用我之前多次使用过的程序来匹配两个文件,但这次它不起作用,我不明白为什么。合并两个文件的脚本

下面是代码:

use strict; 
use warnings; 
use vars qw($damID $damF $damAHC $prog $hash1 %hash1 $info1 $ID $sire $dam $F $FB $AHC $FA $hash2 %hash2 $info2); 


open (FILE1, "<damF.txt") || die "$!\n Couldn't open damF.txt\n"; 
my $N = 1; 
while (<FILE1>){ 
    chomp (my $line=$_); 
    next if 1..$N==$.; 
    my ($damID, $damF, $damAHC, $prog) = split (/\t/, $line); 
     if ($prog){ 
      $hash1 -> {$prog} -> {info1} = "$damID\t$damF\t$damAHC"; 
     } 


    open (FILE2, "<whole pedigree_F.txt") || die "$!\n whole pedigree_F.txt \n"; 
    open (Output, ">Output.txt")||die "Can't Open Output file"; 

    while (<FILE2>){ 
     chomp (my $line=$_); 
     next if 1..$N==$.; 
     my ($ID, $sire, $dam, $F, $FB, $AHC, $FA) = split (/\t/, $line); 
     if ($ID){ 
      $hash2 -> {$ID} -> {info2} = "$F\t$AHC"; 
     } 
      if ($ID && ($hash1->{$prog})){ 
      $info1 = $hash1 -> {$prog} -> {info1}; 
      $info2 = $hash2 -> {$ID} -> {info2}; 
      print "$ID\t$info2\t$info1\n"; 
     } 
    } 
} 


close(FILE1); 

close FILE2; 
close Output; 

print "Done!\n"; 

,并从两个输入文件格式这些片段:

文件1:

501093 0 0 3162 
2958 0 0 3163 
1895 0 0 3164 
1382 0 0 3165 
2869 0 0 3166 
2361 0 0 3167 
754  0 0 3168 
3163 0 0 3169 

文件2:

49327 20543 49325 0.077 0.4899 0.808 0.0484 
49328 15247 49326 0.0755 0.5232 0.8972 0.0499 
49329 27823 49327 0.0834 0.5138 0.8738 0.0541 

我想匹配column 4 in file 1column 1 in file 2的值。

然后我还想打印从columns 2 and 3 in file 1columns 3 and 5 in file 2的匹配值。

此外,它可能是值得一提的每个文件上有大约条目。

这是我得到的输出:

11476 0.0362 0.3237 501093 0 0 
11477 0.0673 0.4768 501093 0 0 
11478 0.0443 0.2619 501093 0 0 

注意,它不是通过我创建的第一个散列循环。

+2

怎么回事?第二个文件名中的空间是否有可能抛弃?你有什么错误吗? – Ilion

+0

请添加您想要的输出 – dawg

+0

第一个散列似乎没有循环。它几乎看起来像使用vars qw();没有在文件上工作 – user7675703

回答

1

在SQLite中创建两个表。将TSV加载到它们中。做一个SQL连接。它会更简单,更快捷。

Refer to this answer about how to load data into SQLite。在你的情况下,你想要.mode tabs

sqlite> create table file1 (col1 int, col2 int, col3 int, col4 int); 
sqlite> create table file2 (col1 int, col2 int, col3 int, col4 numeric, col5 numeric, col6 numeric, col7 numeric); 
sqlite> .mode tabs 
sqlite> .import /path/to/file1 file1 
sqlite> .import /path/to/file2 file2 

有许多方法可以改进这些表格,但我不知道您的数据是什么。使用你自己的更好的名字。您还需要声明主键和外键以及indexes以加快速度。

现在,您可以使用众所周知的查询语言,而不是一堆自定义代码,以易于操作的格式存储数据。

我想在文件1中文件匹配从塔4的值,其中列1 2

然后我还要打印在文件1从2列和第3匹配值并在文件第3和5 2.

您可以用两个表之间的SQL join做到这一点。

select file1.col2, file1.col3, file2.col3, file2.col5 
from file1 
join file2 on file1.col4 = file2.col1