in reply to RE: Count String Occurrences
in thread Count String Occurrences

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";

Replies are listed 'Best First'.
RE: Count String Occurrences
by Lee (Initiate) on Mar 24, 2000 at 22:31 UTC
    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. :)