Perl substring - How to search for one string in another string

Perl substring FAQ: Can you demonstrate some Perl substring examples?

As a language, Perl is very good at text processing, including dealing with strings and substrings. In this article we'll take a look at some Perl substring manipulations we can perform.

For the purposes of our Perl substring tutorial, let's assume that we have a string defined like this:

$string = "I love pizza, morning, noon, and night. I love pizza!";

Given that setup, let's look at how various Perl substring operators work with this initial string.

Perl substring location - The Perl index function

To find out where the string "pizza" is inside of our initial string, we use the Perl index function, like this:

$loc = index($string, "pizza");
print "$loc\n";

This results in the following output:


As arrays are zero-based, this means that the first occurrence of the string "pizza" was found in the 8th element of the initial string ($string).

Perl substring - Looking from the right first with Perl rindex

As you just saw, the Perl index function works by starting at the beginning of the string, and searching until it gets to the end of the string. There is also a Perl rindex function that does just the opposite; it begins at the end of the string, and works its way forward to the beginning of the string, looking for your search text.

Here's almost the exact same code, but using the Perl rindex function instead of index:

$loc = rindex($string, "pizza");
print "$loc\n";

The output from this code is:


which is really the 48th character position in the string.

Perl substring - What happens if your search string isn't found

If Perl can't find your substring in the other string, the index and rindex functions will return -1. For instance, this following code snippet:

$string = "I love pizza, morning, noon, and night. I love pizza.";
$loc = index($string, "hot dogs");
print "$loc\n";

results in this output: