使用Perl中的哈希计数

时间:2014-04-25 15:25:13

标签: perl count hash

我正在尝试确定我的哈希中是否存在某个ID,以及它是否以哈希值存储计数:这就是我所拥有的:

#!/usr/bin/perl
open (INFILE, "parsedveronii.txt")
or die "cannot find infile";

while ($file=<INFILE>){
    @array=split "\t", $file;
    $hash{$array[1]}= ""; #the keys in my hash are subject IDS  
}

open (INFILE1, "uniqueveroniiproteins.txt")
or die "cannot find infile";

while ($file1=<INFILE>){
    @array = split "\n", $file1; #array[0] also contains subject IDs
    if (exists ($hash{$array[0]})){ #if in my hash exists $array[0], keep count of it
    $count++;
    }
    $hash{$array[1]{$count}}=$hash{$array[1]{$count}} +1;#put the count in hash
}
use Data::Dumper;
print Dumper (\%hash);

由于某种原因,它没有执行计数,任何想法?任何帮助表示赞赏。

1 个答案:

答案 0 :(得分:3)

始终在每个脚本及每个脚本的顶部加入use strict;use warnings;

你在第二个文件循环中的阴谋似乎有点人为。如果您只是试图计算主题ID,那么这样做会更简单。

以下是您的代码的清理版本,按我的意图执行。

#!/usr/bin/perl

use strict;
use warnings;
use autodie;

open my $fh, '<', "parsedveronii.txt";

my %count;
while (my $line = <$fh>){
    chomp $line;
    my @array = split "\t", $line;
    $count{$array[1]} = 0; #the keys in my hash are subject IDS  
}

open $fh, '<', "uniqueveroniiproteins.txt";

while (my $line = <$fh>){
    chomp $line;
    my @array = split "\t", $line; #array[0] also contains subject IDs
    if (exists $count{$array[0]}) { #if in my hash exists $array[0], keep count of it
        $count{$array[0]}++;
    }
}

use Data::Dumper;
print Dumper (\%count);