in reply to Count String Occurrences

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?

Replies are listed 'Best First'.
RE: RE: Count String Occurrences
by japhy (Canon) on Mar 28, 2000 at 09:35 UTC
    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.
RE: RE: Count String Occurrences
by chromatic (Archbishop) on Mar 24, 2000 at 19:15 UTC
    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.
        If you're going to do that to save memory, ditch the array altogether (as an SV tends to be smaller than an AV): my $count = scalar(() = $string =~ /abc/g); The blank list gives us list context, while scalar gets the number of items that would be in the list... if it weren't blank. :)