15. Other Data Transformation
Contents:
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
$x = index(
Perl locates the first occurrence of 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 $x = index( Here are some examples of how this third parameter works: $where = index("hello world","l"); # returns 2 (first l) $where = index("hello world","l",0); # same thing $where = index("hello world","l",1); # still same $where = index("hello world","l",3); # now returns 3 # (3 is the first place greater than or equal to 3) $where = index("hello world","o",5); # returns 7 (second o) $where = index("hello world","o",8); # returns -1 (none after 8)
Going the other way, you can
scan from the right to get the rightmost occurrence using
$w = rindex("hello world","he"); # $w gets 0 $w = rindex("hello world","l"); # $w gets 9 (rightmost l) $w = rindex("hello world","o"); # $w gets 7 $w = rindex("hello world","o "); # now $w gets 4 $w = rindex("hello world","xx"); # $w gets -1 (not found) $w = rindex("hello world","o",6); # $w gets 4 (first before 6) $w = rindex("hello world","o",3); # $w gets -1 (not found before 3) |
|