2013-11-23 71 views
0

我有一個表(txt),我想要讀入perl並將不同的列存儲在具有相同鍵的單個哈希中。詳細表看起來是這樣的:在哈希表中存儲txt數據

(第一列:ID, 第二列:父母, 第三列:性別, 第四列:affection_status)

A10米沒有

A2 0 F無

A3 A1A2中號沒有

A4 A1A2˚F是

A5 A1A2˚F是

B10米沒有

我讀計算器(Parse text file and store fields in hash table in Perl)舊線程和想出了這個:

#!/usr/local/bin/perl 

use strict; 

my %pedigree=(); 
my $file = "pedigree.txt"; 

open (pedigree,'<','pedigree.txt') or die ("Cannot open file"); 

while (<pedigree>) { 
    chomp; 
    my ($ID,$parents,$gender,$affection_status)=split /\t/; 
    $pedigree{$ID} = [$parents, $gender, $affection_status]; 

}; 

我想要做的是創造散列(父母,gender,affection_status都具有相同的密鑰(ID)。然後我想在輸入密鑰時看到各個值:

print "Please enter patient ID: "; #user input required: patient ID 
chomp(my $ID = <STDIN>); 

print "$ID gender: $pedigree{gender}{$ID}\n 
$ID affected: $pedigree{affection_status}{$ID}\n 
$ID parents: $pedigree{parents}{$ID} \n" ; 

但是,當我運行這個時,我沒有輸出。誰能幫我這個?預先感謝您的幫助

+0

'使用warnings'。 – TLP

回答

0

%pedigree應該在你想從它讀取同樣的方式進行填充,

my @cols = qw(parents gender affection_status); 
while (<pedigree>) { 
    chomp; 
    my ($ID, @arr) = split /\t/; 
    $pedigree{ $cols[$_] }{$ID} = $arr[$_] for 0 .. $#cols; 
} 
+0

哇,這很快:-)非常感謝! – Pustefix

+0

@Pustefix你也可以改變輸出,'$ pedigree {$ ID} [1]'將用於性別 –