Open In App

Perl | index() Function

Improve
Improve
Like Article
Like
Save
Share
Report

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 = "Geeks 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 = "Geeks are the best";
 
# Defining the starting Index
$pos = 3;
 
# Using index() to search for substring
$index = index ($string, 'Geeks', $pos);
 
# Printing the position of the substring
print "Position of 'Geeks' in the string: $index\n";


Output:

Position of 'Geeks' 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 = 'Geeks for Geeks';
$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 = 'Geeks for Geeks';
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 – 

 



Last Updated : 06 Mar, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads