2017-03-08 121 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