in reply to counting the number of occurrances of a word using regex

And in the spirit of TIMTOWTDI:

my $string = "The quick brown fox jumps over the lazy dog."; my $count = 0; $count++ while $string =~ /(the)/gi;

This is useful if, for example, you want to operate on a particular occurence of a match. For example, if you wanted to grab the second occurence of particular item in every line of log file:

while (<IN_FILE>) { my $count = 0; MATCH: while (/(\Q$some_string\E)/gi) { $count++; if ( 2 == $count ) { # do something last MATCH; } } }

Cheers,
Ovid

New address of my CGI Course.
Silence is Evil (feel free to copy and distribute widely - note copyright text)

Replies are listed 'Best First'.
Re: counting the number of occurrances of a word using regex
by Abigail-II (Bishop) on Dec 03, 2002 at 12:40 UTC
    There's no point in putting parenthesis around the search pattern, is there? I find it remarkably that 3 out of the 5 followups so far put parenthesis around the search pattern, without using $1.

    Abigail

      You're right. I was just a-cuttin' and a-pastin' and not paying attention. That's a very bad habit of mine. Thanks for the reminder.

      Cheers,
      Ovid

      New address of my CGI Course.
      Silence is Evil (feel free to copy and distribute widely - note copyright text)