To find the indices of all occurrences of a substring in Perl, you can use the index
function in a loop to find matches and store their indices.
In this example,
$str
with a string value.$substr
to store the substring we want to find.index
function to find matches and store their indices.my $str = "Hello Hello Hello";
my $substr = "Hello";
my @indices;
my $pos = -1;
while (($pos = index($str, $substr, $pos + 1)) != -1) {
push @indices, $pos;
}
print "Indices of all occurrences: @indices\n";
Indices of all occurrences: 0 6 12
In this example,
$str
and $substr
with different values.index
function to find matches and store their indices.my $str = "apple banana cherry banana";
my $substr = "banana";
my @indices;
my $pos = -1;
while (($pos = index($str, $substr, $pos + 1)) != -1) {
push @indices, $pos;
}
print "Indices of all occurrences: @indices\n";
Indices of all occurrences: 6 20
In this tutorial, we learned How to find the Indices of All Occurrences of Substring in Perl language with well detailed examples.