Beefy Boxes and Bandwidth Generously Provided by pair Networks
Syntactic Confectionery Delight
 
PerlMonks  

Re: Count values in a hash

by ack (Deacon)
on Jan 11, 2011 at 21:53 UTC ( [id://881776]=note: print w/replies, xml ) Need Help??


in reply to Count values in a hash

Head the other responders' replies. Failure to de-reference your hash and array are the source of the difficulty as the other responders noted.

Here is a quick, short set of code that does what I believe your looking to do. I include it just so that you can see one way to do it. Of course, as in all of Perl, TMTODI.

Cheers.

#!/usr/bin/perl use strict; use warnings; my $VAR1 = { 'A2M' => [ 'C972Y', 'A423W' ], 'A4GALT' => [ 'W261X', 'P251L', 'P251S', 'A219V' ] }; my $numKeys = scalar(keys %{$VAR1}); print "gene total x\n"; foreach my $key (keys %{$VAR1}){ my @values = @{$VAR1->{$key}}; my $numValues = scalar(@values); my $numXs = 0; $numXs += ($_ =~ /X/g)?1:0 foreach(@values); print "$key $numValues $numXs\n"; } exit(0);

The resulting output is:

gene total x A2M 2 0 A4GALT 4 1

Which is what I believe you are after.

The only difficulty is that the pattern match, $_ =~ /X/g is not very general...it wouldn't, for instance, see multiple occurances of 'X' in a value (you, the OP, didn't specify what to do if such an occurance presented itself) nor would it distinguish upper case 'X' from a lower case 'x' (you didn't specify if that mattered). But I figured either you'd already know how to handle those situations or they would be good explorations of Perl for you.

Also note that I just initialize the hash with the example that you gave rather than reading it in from a file because I felt that it would just obscure the main body.

ack Albuquerque, NM

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://881776]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others learning in the Monastery: (5)
As of 2024-03-19 08:51 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found