Hi all,

I have a hash of the following format

$VAR1 = { 'A2M' => [ 'C972Y', 'A423W' ], 'A4GALT' => [ 'W261X', 'P251L', 'P251S', 'A219V' ] };

What I would like to do is to count the values for each key and also to note the number of values that contain an X. Thus, I would like to have a table like this:

gene total x A2M 2 0 A4GALT 4 1

The code I used to load the file into the hash is

my %hash; while(<INFILE>) { chomp; my $line = $_; my ($key, @val) = split /\t/, $line, 2; push @{ $hash{$key} }, @val; }

And the script that I though would work for the second part but did not is as follows:

my $totalcount = 0; my $xcount = 0; foreach my $k (sort keys %hash) { print "Current key is\t" . $k . "\n"; my @values = $hash{$k}; foreach $i (@values){ $xcount++ if $i =~ /(X)/; $totalcount++; } print $k . "\t" . $totalcount . "\t" . $xcount . "\n";

I would appreciate any help. when I try to check whether the value array works properly, I noticed that it does not, however, I could not pinpoint what is exactly wrong with the values array.

Thank you.


In reply to Count values in a hash by sophix

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.