in reply to Counting words..

Wrt the wordcount, you say that you want to match a specific word, but all the solutions so far provided match strings. To illustrate the difference:

my $string = 'Cathy placated her cat, which was trying to catch a caterpillar.'; my $keyword = 'cat'; my $count = 0; ++$count while $string =~ /$keyword/gi; print "Occurrences of '$keyword': $count";

Output: Occurrences of 'cat': 5

If that's not what you want, wrap your keyword in word boundary metacharacters:

$string =~ /\b$keyword\b/gi;

Replies are listed 'Best First'.
Re^2: Counting words..
by No-Lifer (Initiate) on Oct 24, 2005 at 16:50 UTC
    Many thanks for the replies,

    I got it working using $count++ while /$keyword/ig;

    Printing the $count, then re-setting the counter (as I've got it in a loop to count each page searched).

    I'm wrestling with searching for words/strings now (which is semi-working!), and will probably result in a new post!

    Thanks again people,

    NL
      This may prove a bit more efficient:
      $count = () = /$keyword/ig;
      It puts the match into array context, which causes it to return the matches; then the resulting array is taken as a scalar, resulting in the count. This is a somewhat common Perl idiom. And you don't have to reset the counter.

      Of course, if you need to accumulate several counts, make it += instead of =, and do remember to reset the counter.


      Caution: Contents may have been coded under pressure.