Hi Chris,
You are getting only the last line of the file because of this:
> foreach $i (@lines) {
> @words = split(/\s+/, $i);
> }
You reassign the @words array each time, and end up with the last line only
when exiting the foreach loop. You may want to look at 'perldoc -f push' to see
how to add to an array.
Here is how I would likely accomplish this task:
#!/usr/bin/perl -w
use strict;
my %counts;
open(FILE,"file.txt") or die "Can't open file: $!";
my @lines = <FILE>;
close FILE;
for (@lines) {
$counts{$_}++ for (split /\s+/);
}
print qq{$counts{$_} occurances of the word $_\n} for keys %counts;
Cheers,
Kevin
On Tue, Apr 24, 2001 at 10:17:02AM -0500, Chris Brown ([EMAIL PROTECTED]) spew-ed
forth:
> 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";
> }
>
--
Down that path lies madness. On the other hand, the road to hell is
paved with melting snowballs.
--Larry Wall in <[EMAIL PROTECTED]>