Counting frequency of words.

From: Vishal Vasan (vishal.v_at_net-kraft.com)
Date: 02/25/04


Date: Wed, 25 Feb 2004 15:37:26 +0530
To: beginners@perl.org

Hello All,

I have to find the frequency of occurance of all (mail code: This is the
first 8 characters of the line) in a huge file. Instead of doing it in C
I am trying it out in perl. I am trying hashes for this. Whenever a new
code comes, the count has to be incremented.

This is the code that i am trying to build. I am unable to add a new
mail code I find to the hash. It is over writing it. Would somebody
please point out the mistake in the code?

      1 #!/usr/bin/perl
      2
      3 while(<>){
      4 $mailcode = substr($_, 0, 8);
      5 $flag = 0;
      6 foreach my $key (keys %hash){
      7 if($key =~ /$mailcode/){
      8 $hash{$key}++;
     10 $flag = 1;
     11 }
     12 }
     13 if($flag == 0){
     14 %hash = qq($key 0);
     15 }
     16 }
     18
     19 print "%hash";

Regards,
Vishal Vasan.