How to find all occurrences of a string in another string using Perl

How to find all occurrences of a string in another string using Perl?

#!/usr/bin/perl
use strict;
use warnings;

my $string = 'needle in the haystack. needle again. needle';
my $find_me = 'needle';
my $offset = 0;
my $result = index($string, $find_me, $offset);

while ($result != -1) {
   print "Found $find_me at $result\n";
   $offset = $result + 1;
   $result = index($string, $find_me, $offset);
}

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>