Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

Dear Monks,
I need to use the index function and I found this example:
#!/usr/bin/perl use strict; use warnings; my $string = 'perlmeme.org'; my $char = 'e'; my $offset = 0; my $result = index($string, $char, $offset); while ($result != -1) { print "Found $char at $result\n"; $offset = $result + 1; $result = index($string, $char, $offset); }

This is very straightforward, BUT, how could one find all occurences of a string that is now known exactly beforehand?
Consider the string:
$string = 'IIIIMMMMMMMOOOOOOOOOOMMMMMMMMMMMMMMMIIIIIIMMMMOOOO';

and say you would like to find all occurences (starting positions and lengths) of the M's substrings.
How do I need to proceed?

Replies are listed 'Best First'.
Re: how do you use the index function on this example?
by Anonymous Monk on Sep 21, 2015 at 19:48 UTC
    Ah, never mind, I found this solution:
    while($string=~/(M+)/g) { ($start, $end) = ($-[0], $+[0]); print $start."\t".$end."\n"; }

    Thanks

      And you don't even need the capturing parentheses:

      c:\@Work\Perl>perl -wMstrict -le "my $string = 'IIIIMMMMMMMOOOOOOOOOOMMMMMMMMMMMMMMMIIIIIIMMMMOOOO'; ;; while ($string =~ /M+/g) { my ($start, $end) = ($-[0], $+[0]); print qq{start $start, end $end}; } " start 4, end 11 start 21, end 36 start 42, end 46
      Note that  @+ holds the positions of the first character after matched sub-strings!


      Give a man a fish:  <%-{-{-{-<