Chapter 15. Other Data Transformation

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 index 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 zero. If it’s one character later, you get a one, and so on. If the substring can’t be found in string, you get negative one.

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 each 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 ...

Get Learning Perl on Win32 Systems now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.