Vishal Vasan wrote:
>
> 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";
This line
%hash = qq($key 0);
sets the entire hash to
%hash = ("$key 0" => undef);
but there's no need to search through the hash to see if a key already
exists: you can just increment an element and Perl will create it for you
if it's not already there. Also, you must
use strict; # always
use warnings; # usually
and never call use variable names like %hash, @array etc. The % tells us that
it's a hash - use the name to say something useful.
This program will do what you want.
use strict;
use warnings;
my %frequency;
while (<>) {
my $mailcode = substr($_, 0, 8);
$frequency{$mailcode}++;
}
HTH,
Rob
--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
<http://learn.perl.org/> <http://learn.perl.org/first-response>