On 15/07/2011 16:58, Matt 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.

Hi Matt

A call to split() can be very useful for quickly stripping leading and
trailing whitespace (including any terminating newline) even if there is
onlt a single field in each record.

The program below uses this in a solution to your problem, but if you
need to maintain the order of the words in the original file then
something more will be needed.

HTH,

Rob


use strict;
use warnings;

my %count;

while (<DATA>) {
  $count{$_}++ foreach split;
}

print "$_ ($count{$_})\n" foreach keys %count;

__DATA__
blue
red
red
red
orange
orange
green

**OUTPUT**

green (1)
blue (1)
orange (2)
red (3)


--
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/


Reply via email to