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: ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access