in reply to Counting instances of words

The problem is here:
while (<$in>) { s/\band\b/$word/ig; # <- Here you make all the substitutions while (/\band\b/ig) # <-... and here nothing happens! { ++$count; } print($out "$_\n"); }

s/// will return the number of occurrences, so...

while (<$in>) { $code = s/\band\b/$word/ig; # <- Here you make all the substit +utions ## UPDATE: ## $code += s/\band\b/$word/ig; # <- Here you make all ## Sorry for the mistake (thanks blazar!) print($out "$_\n"); }

should works

citromatik

Replies are listed 'Best First'.
Re^2: Counting instances of words
by scarymonster (Initiate) on May 25, 2007 at 16:43 UTC
    Thanks for your help. Tried this, and $code appears to be empty. I've declared it outside the While loop, but it prints out as null. Should this contain the total substitutions?
      Thanks for your help. Tried this, and $code appears to be empty. I've declared it outside the While loop, but it prints out as null. Should this contain the total substitutions?

      Well, for one thing I wouldn't regard $code as a particularly good variable name. Then, if you want the total number of substitutions, you must accumulate them:

      $count += s/\band\b/$word/ig;