1: sub count_occurrences{
   2:   my($part, $whole, $cs)=@_;
   3: 
   4:   # $part -- the text you're searching for
   5:   # $whole - the string within you're searching
   6:   # $cs   -- case sensitive? 1=yes, 0=no  (may be omitted for non cs search)
   7: 
   8:   my($count)=0; 
   9:   my($null)="\0";
  10:   if($cs==1){
  11:    while($whole=~/$part/s){
  12:     $count++;
  13:     $whole=~s/$part/$null/;
  14:    }
  15:   }else{
  16:    while($whole=~/$part/is){
  17:     $count++;
  18:     $whole=~s/$part/$null/i;
  19:    }
  20:   }
  21:   return $count;
  22: }

Replies are listed 'Best First'.
RE: Count String Occurrences
by nate (Monk) on Mar 24, 2000 at 10:49 UTC
    Can also be done with this line:

    my $num = ($whole =~ s/$part/$part/g);

    add an "i" to the end of the regex if you want to be case insensitive.

    Is there another way?

      I'd suggest using:
      $pattern = "whatever"; $mode = "(?"; $mode .= "i" if $case_insensitive; $mode .= "s" if $dot_matches_all; $mode .= "m" if $multiline_match; $mode .= "x" if $allow_comments; $mode .= ")"; $count++ while $string =~ /$mode$pattern/o;
      Voila.
      From the Bizzare Code You'll Never Use For Real files:
      my $string = "abcabcacbabc"; my @num_times = split(/abc/, "$string "); print scalar @num_times -1, "\n";
        Or this my $string = "abcabcacbabc"; my @num_count=($string =~ m/abc/g); print scalar @num_count; the advantage is that the array created contains 1's only where as the array created in your script contains search string which is longer (in the example you gave three times longer). The array gets trashed when out of scope but why thrash memory. Lee.