Perl has always been known for its text processing and manipulation abilities. This article examines the Perl string handling API in greater detail, explaining how you can use Perl's string functions to (among other things) print and format strings, split and join string values, alter string case, and perform regular expression searches.
Next up, the substr() function. As the name implies, this is the function that allows you to slice and dice strings into smaller strings. Here's what it looks like:
substr(string, start, length)
where "string" is a string or string variable, "start" is the position to begin slicing at, and "length" is the number of characters to return from "start".
Here's an example which demonstrates how this works:
#!/usr/bin/perl
$str = "The cow jumped over the moon, purple pumpkins all over the world
rejoiced.";
# returns "purple pumpkin"
print substr($str, 30, 14);
You can use the case-sensitive index() function to locate the first occurrence of a character in a string,
#!/usr/bin/perl
$str = "Robin Hood and his band of merry men";
# returns 29
print index($str, "r");
and the rindex() function to locate its last occurrence.
#!/usr/bin/perl
$str = "Robin Hood and his band of merry men";
# returns 33
print rindex($str, "m");
You can also tell these functions to skip a certain number of characters before beginning the search - consider the following example, which demonstrates by beginning the search after skipping the first five characters in the string.
#!/usr/bin/perl
$str = "Robin Hood and his band of merry men";
# skips 5 "o"s
# returns 7 for the first "o" in "Hood"
print index($str, "o", 5);