--- Chris Brown <[EMAIL PROTECTED]> wrote:
> 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";
> }

TMTOWTDI :o]

 #!/usr/local/bin/perl -w

 use strict 
 open (FILE,$0) or die $!; # this reads itself
 my($data,%count); 
 { local $/ = undef;       # erases the record seperator for this block
   $data = <FILE>;         # slurps in the whole file to $data
 }   
 close(FILE);              # good habit
 map { $count{$_}++ } $data =~ /(\w+)/sog; # watch the context!
 print map { "$count{$_} occurances of '$_'\n" } sort keys %count;

Perl is a wonderfully concise language.
The above is strictly given as an example of a few performance tricks
that are worth researching. =o)

Paul
 

__________________________________________________
Do You Yahoo!?
Yahoo! Auctions - buy the things you want at great prices
http://auctions.yahoo.com/

Reply via email to