2013-11-23 73 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]'将用于性别 –