Question: How can I find the number of times a word is in a block of text in Perl?

For example my text file is this:

```
#! /usr/bin/perl -w
# The 'terrible' program - a poorly formatted 'oddeven'.
use constant HOWMANY => 4; $count = 0;
while ( $count < HOWMANY ) {
  $count++;
  if ( $count == 1 ) {
    print "odd\n"; 
  } elsif ( $count == 2 ) { 
    print "even\n";
  } elsif ( $count == 3 ) {
    print "odd\n";
  } else { # at this point $count is four.
    print "even\n";
  }
}  

```

I want to find the number of "count" word for that text file. File is named terrible.pl

Idealy it should use **regex** and with **minimum** number of line of code.

**EDIT:** This is what I have tried:

```
use IO::File;
my $fh = IO::File->new('terrible.pl', 'r') or die "$!\n";
my %words;
while (<$fh>) {
  for my $word ($text =~ /count/g) {
  print "x";
    $words{$word}++;
  }
}
print $words{$word};

```

Answer: 
If you are trying to count how many times appears the word "count", this will work:

```
my $count=0;
open(INPUT,"<terrible.pl");
while (<INPUT>) {
    $count++ while ($_ =~ /count/g);
}
close(INPUT);
print "$count times\n";

```
You can probably use something like so:

```
my $fh = IO::File->new('test.txt', 'r') or die "$!\n";
my %words;
while (<$fh>) {
  for my $word (split / /) {
    $words{$word}++;
  }
}

```

That will give you an accurate count of every "word" (defined as a group of characters separated by a space), and store it in a hash which is keyed by the word with a value of the number of the word which was seen.