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

Rating 3.00 out of 5

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);
}

Related posts:

  1. Greedy Search in Perl Regular Expressions
  2. Alter Regular Expression Match Position in Perl
  3. How to know if document exists on a URL in perl
  4. How to get elements from one array but not in another array

Leave a Reply

 

 

 

You can use these HTML tags

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>