my %words;
while (<>) {
# read input line by line...
# remove trailing new line
chomp;
my $word = $_;
$words{$word}++;
}
foreach my $word (sort keys %words) {
print "$word ($words{$word})\n";
}
------
you can run the script like this : cat file.txt | perl script.pl
It can be a lot shorter but I tried to write verbosely so you could
experiment.
cheers.
- jose biskofski
On Fri, Jul 15, 2011 at 10:58 AM, Matt <[email protected]> wrote:
> I have a file with lines like so but the number of them is in the
> thousands instead of seven lines:
>
> blue
> red
> red
> red
> orange
> orange
> green
>
> I want it to count the occurances of each word it finds in the file.
> So output on this small file would be:
>
> blue (1)
> red (3)
> orange (2)
> green (1)
>
> The contents of the file are sorted already. Any ideas how to do this?
> Thanks.
>
> --
> To unsubscribe, e-mail: [email protected]
> For additional commands, e-mail: [email protected]
> http://learn.perl.org/
>
>
>