perl function index
The index
function in Perl is used to find the position of a substring within a string. It takes two arguments: a string to search within, and a substring to search for. If the substring is found within the string, index
returns the position of the first occurrence of the substring, counting from 0. If the substring is not found, index
returns -1.
Here's an example that demonstrates how to use index
:
#!/usr/bin/perl use strict; use warnings; # Define a string my $string = "The quick brown fox jumps over the lazy dog"; # Find the position of the word "fox" my $position = index($string, "fox"); # Print the position of "fox" print "Position of 'fox': $position\n"; # Find the position of the word "cat" $position = index($string, "cat"); # Print the position of "cat" print "Position of 'cat': $position\n";
In this example, we start by defining a string The quick brown fox jumps over the lazy dog
. We then use the index
function to find the position of the word "fox" within the string. Since "fox" is present in the string, index
returns the position of the first occurrence of "fox", which is 16. We print this position to the console.
We then use index
again to find the position of the word "cat" within the string. Since "cat" is not present in the string, index
returns -1. We print this position to the console as well.
Note that index
is case-sensitive, so it will only find exact matches of the substring. If you need to perform a case-insensitive search, you can convert the string and substring to lowercase or uppercase using the lc
or uc
functions before calling index
.