将文本数据存储在哈希表中

时间:2013-11-23 13:54:48

标签: perl

我有一个表(txt),我想读入perl并将不同的列存储在具有相同键的单个哈希中。详细信息表格如下所示:

(第一栏:身份证, 第二栏:父母, 第三栏:性别, 第四栏:affection_status)

A1 0 m no

A2 0 f否

A3 A1A2 m no

A4 A1A2 f是

A5 A1A2 f是

B1 0 m no

我在stackoverflow(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];

};

我想要做的是创建哈希(父母,性别,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" ;

然而,当我运行它时,我没有输出。谁能帮我这个?提前感谢您的帮助

1 个答案:

答案 0 :(得分:0)

%pedigree的填充方式应与您想要的相同,

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