user3268152
user3268152

Reputation: 31

Counting using Hashes in Perl

I am trying to determine if a certain ID is present in my hash and if it is store the count in hash: this is what I have:

#!/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);

for some reason it's not executing the count, any ideas? Any help is appreciated.

Upvotes: 1

Views: 607

Answers (1)

Miller
Miller

Reputation: 35218

Always include use strict; and use warnings; at the top of each and EVERY script.

Your machinations in the second file loop seem a little contrived. If you're just trying to count the subject ids, that is done a lot simpler.

The following is a cleaned up version of your code, doing what I interpret as your intention.

#!/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);

Upvotes: 3

Related Questions