珀尔 | index()函数
此函数返回字符串(或文本)中给定子字符串(或模式)第一次出现的位置。我们可以指定起始位置。默认情况下,它从头开始搜索(即从索引零开始)。
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.
示例 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
示例 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
这里,在第二个示例中,位置设置为“3”,即开始搜索的起始索引是从第 3 个位置开始。因此,在字符串中找不到子字符串。