On 10/06/2010 03:17, Peng Yu wrote:
I can't find an existing perl subroutine (in the library) to find
every occurrence of a substring in a string. The following webpage
"Example 3b. How to find every occurrence" uses a loop to do so. But
I'd prefer a subroutine. Could you let me know if such a subroutine is
available in perl library?

http://perlmeme.org/howtos/perlfunc/index_function.html


It is possible that index() is faster than regular expressions, but I would write the code below.

HTH,

Rob

use strict;
use warnings;

print occurrences('xabbabcabdabeab', 'ab');

sub occurrences {
  my ($str, $sub) = @_;
  my $n;
  $n++ while $str =~ /\Q$sub/g;
  $n;
}

__END__

**OUTPUT**

5

--
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/


Reply via email to