index
indexSTR,SUBSTR,OFFSETindexSTR,SUBSTR
This function searches for one literal string within another.
It returns the position of the first occurrence of
SUBSTR in STR. The
OFFSET, if specified, says how many
characters from the start to skip before beginning to look. Positions
are based at 0. If the substring is not found, the function returns one
less than the base, ordinarily –1. To
work your way through a string, you might say:
$pos = –1;
while (($pos = index($string, $lookfor, $pos)) > –1) {
say "Found at $pos"; $pos++;
}Offsets are always by programmer-visible characters (i.e., codepoints), not by user-visible characters (graphemes). The offset is in bytes only if you have already decoded from abstract characters into some serialization scheme, like UTF-8 or UTF-16. See Chapter 6.
To work with strings as sequences of graphemes instead of
codepoints, see the index, rindex, and pos methods for the CPAN Unicode::GCString module.
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