Home » Howtos » Perlfunc » Rindex function |
The rindex()
function is used to determine the position of a character in a string starting at the end of the string. We recommend that you first read our index() howto.
rindex()
works exactly the same as index()
except that it returns the index of the last occurrence of a letter or substring in the string.
We want to find the last occurrence of the letter "m" in the string "perlmeme.org".
#!/usr/bin/perl use strict; use warnings; my $string = 'perlmeme.org'; my $char = 'm'; my $result = rindex($string, $char); print "Result: $result\n";
This program gives you:
Result: 6
Just like for index()
if the string doesn't contain the letter, rindex()
will return a -1. For example, we can look for the letter "L" in the string "perlmeme.org":
#!/usr/bin/perl use strict; use warnings; my $string = 'perlmeme.org'; my $char = 'L'; my $result = rindex($string, $char); print "Result: $result\n";
The program outputs:
Result: -1
If the letter we're searching for appears more than once in the string, rindex()
return the index of the first occurrence of the letter.
#!/usr/bin/perl use strict; use warnings; my $string = 'perlmeme.org'; my $char = 'e'; my $result = rindex($string, $char); print "Result: $result\n";
This program gives you:
Result: 7
The offset parameter for rindex()
works slightly differently to the offset parameter for index()
.
In index()
the character of substring will be searched for starting at the offset position. For example, the first occurrence of the letter 'e' in the string "perlmeme.org" is at position 1. If we want to find the second occurrence, we set the offset to 2.
With rindex()
we start at the offset position and look backwards. The last occurrence of the letter 'e' is at position 7. So to find the second last occurrence we set the offset to 6.
#!/usr/bin/perl use strict; use warnings; my $string = 'perlmeme.org'; my $char = 'e'; # The first 'e' was at position 1, so let's start # looking again at position 2 my $offset = 6; my $result = rindex($string, $char, $offset); print "Result: $result\n";
The program outputs:
Result: 5
To find (and do something with) every occurrence of a character in a string using rindex()
, you could use index()
in a loop, decrementing the offset each time. Note that when using an offset, we need to tell rindex()
to start at the back of the string (otherwise it starts at 0 which returns no results).
#!/usr/bin/perl use strict; use warnings; my $string = 'perlmeme.org'; my $char = 'e'; # Start at the end of the string my $offset = length($string); my $result = rindex($string, $char, $offset); while ($result != -1) { print "Found $char at $result\n"; $offset = $result - 1; $result = rindex($string, $char, $offset); }
When we run this program, we get the following output:
Found e at 7 Found e at 5 Found e at 1
perldoc -f rindex perldoc -f index index()