Perl | index() Function

This function returns the position of the first occurrence of given substring (or pattern) in a string (or text). We can specify start position. By default, it searches from the beginning(i.e. from index zero).

Syntax: # Searches pat in text from given index index(text, pat, index) # Searches pat in text index(text, pat) Parameters:

  • text: String in which substring is to be searched.
  • pat: Substring to be searched.
  • index: Starting index(set by the user or it takes zero by default).

Returns: -1 on failure otherwise Position of the matching string.

Example 1: 

Perl




#!/usr/bin/perl
 
# String from which Substring
# is to be searched
$string = "Beginner are the best";
 
# Using index() to search for substring
$index = index ($string, 'the');
 
# Printing the position of the substring
print "Position of 'the' in the string: $index\n";


Output:

Position of 'the' in the string: 10

Example 2: 

Perl




#!/usr/bin/perl
 
# String from which Substring
# is to be searched
$string = "Beginner are the best";
 
# Defining the starting Index
$pos = 3;
 
# Using index() to search for substring
$index = index ($string, 'Beginner', $pos);
 
# Printing the position of the substring
print "Position of 'Beginner' in the string: $index\n";


Output:

Position of 'Beginner' in the string: -1

Here, in the second example the position is set to β€˜3’, i.e. the starting index from where searching is to begin is from 3rd position. Hence, the substring is not found in the String.

Example – 3: Here we will see what will happen if the string/character we are trying to find is present more than once in the real string.

Perl




#!/usr/bin/perl
 
$string = 'Beginner for Beginner';
$char = 'e';
 
$res = index($string, $char);
 
print("Position of $char is : $res\n");


Output – 

 

Now as we can see it returned the output as 1 which is the first occurrence of β€˜e’. If we have the required character present more than once in our string, index will return the first occurrence by default.

Example – 4 : Here we will see how we can get all the occurrences of a character in the original string.

Perl




#!/usr/bin/perl
my $string = 'Beginner for Beginner';
my $char = 'e';
my $start = 0;
 
my $res = index($string, $char,$start);
 
# Checking till the char is not found
while ($res != -1 ) {
    print("Occurence of $char at $res\n");
 
    # incrementing $start value each iteration
    # so that it doesn't print same index twice
     
    $start=$res+1;
     
    # Finding the index using the updated
    # start value
    $res = index($string,$char,$start);
}


Output –