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:
#!/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"; |
Position of 'the' in the string: 10
Example 2:
#!/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"; |
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.
Recommended Posts:
- Perl | String functions (length, lc, uc, index, rindex)
- Perl | abs() function
- Perl | uc() Function
- Perl | cos() Function
- Perl | int() function
- Perl | sin() Function
- Perl | log() Function
- Perl | each() Function
- Perl | oct() Function
- Perl | hex Function
- Perl | ord() Function
- Perl | chr() Function
- Perl | tell() Function
- Perl | exp Function
- Perl | rand() Function
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



