Perl | rindex() Function

rindex() function in Perl operates similar to index() function, except it returns the position of the last occurrence of the substring (or pattern) in the string (or text). If the position is specified, returns the last occurrence at or before that position.

Syntax:
# Searches pat in text from given Position
rindex text, pattern, Position

# Searches pat in text
rindex text, pattern

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 last occurence.

Example 1:

filter_none

edit
close

play_arrow

link
brightness_4
code

#!/usr/bin/perl -w
  
$pos = rindex("WelcomeToGeeksforGeeksWorld", "eks");
print "Position of eks: $pos\n";
  
# Use the first position found as the offset 
# to the next search.
  
# Note that the length of the target string is
# subtracted from the offset to save time.
$pos = rindex("WelcomeToGeeksforGeeksWorld"
                          "eks", $pos - 3 );
print "Position of eks: $pos\n";

chevron_right


Output:

Position of eks: 19
Position of eks: 11

Example 2:

filter_none

edit
close

play_arrow

link
brightness_4
code

#!/usr/bin/perl -w
  
$pos = rindex("GeeksforGeeks", "eks");
print "Position of eek: $pos\n";
  
# Use the first position found as the 
# offset to the next search.
  
# Note that the length of the target string is
# subtracted from the offset to save time.
$pos = rindex("GeeksForGeeks", "eks", $pos - 2);
print "Position of eek: $pos\n";

chevron_right


Output:

Position of eek: 10
Position of eek: 2


My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

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.




Article Tags :
Practice Tags :


Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.