What is the index() method in Perl?

Overview

The index() method is used to find the index position of a character or sub-string in a string.

Syntax

# for a character
index(string, char);
# for a sub-string
index(string, sub-string);

Return value

This method returns the index position of the character char or the sub-string sub-string in the string string.

# get index positions of characters and sub-strings
print index("Educative is great", "E"); # 0
print("\n");
print index("Shots and authors", "s"); # 4
print("\n");
print index("Courses and students", "and"); # 8
print("\n");
print index("Perl is great!", "z"); # -1 not found

Code explanation

  • Line 3: We check the index of E in the string Educative is great. Then, we print the index that is returned.
  • Line 5: We check the index of s in the string Shots and authors and print the returned value.
  • Line 7: We check the index of and in the string Courses and students and print the returned value.
  • Line 9: We check the index of z in the string Perl is great and print the returned value.

Free Resources