O'Reilly logo

Learning Perl, Second Edition by Randal L. Schwartz, Tom Christiansen

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

15.1. Finding a Substring

Finding a substring depends on where you have lost it. If you happen to have lost it within a bigger string, you're in luck, because index can help you out. Here's how it looks:

$x = index($string,$substring);

Perl locates the first occurrence of substring within string, returning an integer location of the first character. The index value returned is zero-based; if the substring is found at the beginning of the string, you get a 0. If it's one character later, you get a 1, and so on. If the substring can't be found in string, you get -1.

Take a look at these:

$where   = index("hello","e");                 # $where gets 1
$person  = "barney";
$where   = index("fred barney",$person);       # $where gets 5
@rockers = ("fred","barney");
$where   = index(join(" ",@rockers),$person);  # same thing

Notice that both the string being searched and the string being searched for can be a literal string, a scalar variable containing a string, or even an expression that has a string value. Here are some more examples:

$which = index("a very long string","long"); # $which gets 7
$which = index("a very long string","lame"); # $which gets -1

If the string contains the substring at more than one location, the index function returns the leftmost location. To find later locations, you can give index a third parameter. This parameter is the minimum value that will be returned by index, allowing you to look for the next occurrence of the substring that follows a selected position. It looks like this: ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required