The problem is that you override the (global) array @words for each line.
You go through @lines and the split overrides @words!
While we are at it... ;-)

You do not need that many loops. The programm will be much simpler like
that:

open(FILE, "yourFileName");

while ($line = <FILE>) { #no need to read the file into an array
  @words = split/\s+/, $line; #just process each line as it comes
  foreach $word (@words) {
    $wordcount{$word} += 1; #no need to initialize the hash with 0,
                            #perl does that for you
  }
}
close(FILE);

foreach $word (keys %wordcount) {
  print $word, ": ", $wordcount{$word}, "\n";
}


hope this helps,

cr

P.S.:
If you have question about the code above, feel free to ask.


On Tue, 24 Apr 2001 10:17:02 -0500, Chris Brown said:

> so...this is suposed to count the words in FILE and return how many occourances of 
>each word there were...its not working for me though....its only returning the count 
>for the last word in the file...help
>  
>  #!/usr/local/bin/perl
>  
>  open (FILE,"../www/main.php3");
>  @lines=<FILE>;
>  close(FILE);
>  
>  foreach $i (@lines) {
>  @words = split(/\s+/, $i);
>  }
>  
>  foreach $word (@words) {
>  $wordcount{"$word"}=0;
>  }
>  
>  foreach $word2 (@words) {
>  $wordcount{"$word2"}+=1;
>  }
>  
>  foreach $key (keys (%wordcount)) {
>          print "$wordcount{$key} occourances of the whord $key\n";
>  }
>  
>  

Reply via email to