← All languages
Perl construct of the day
Random

index

Find the position of a substring within a string.

Description

The index function searches for a substring within a string and returns the position of the first occurrence. If the substring is not found, it returns -1.

An optional third argument specifies the position at which to start searching. This allows finding subsequent occurrences of a substring by calling index repeatedly with increasing positions.

index performs case-sensitive matching. For case-insensitive searches, convert both strings to the same case with lc or uc before searching. The companion function rindex searches from the end of the string.

Arguments

NameDescriptionOptional
STR The string to search in. No
SUBSTR The substring to search for. No
POSITION The position to start searching from. Yes

Example

my $str = 'Hello, World!';
print index($str, 'World');  # 7
print index($str, 'xyz');    # -1
print index($str, 'l', 4);  # 10

Reference