珀尔 | substr()函数
Perl 中的 substr() 从传递给函数的字符串从给定的索引开始直到指定的长度。如果未指定长度,则此函数默认返回从给定索引开始的字符串的剩余部分。如果您想用其他子字符串的那部分,也可以将替换字符串传递给 substr()函数。
这个索引和长度值也可能是负数,这会改变字符串中索引计数的方向。
例如,如果传递了负索引,则子字符串将从字符串的右端返回,如果我们传递负长度,则函数将从字符串的后端留下那么多字符。
Syntax: substr(string, index, length, replacement)
Parameters:
- string: string from which substring is to be extracted
- index: starting index of the substring
- length: length of the substring
- replacement: replacement substring(if any)
Returns: the substring of the required length
注意:参数“length”和“replacement”可以省略。
示例 1
#!/usr/bin/perl
# String to be passed
$string = "GeeksForGeeks";
# Calling substr() to find string
# without passing length
$sub_string1 = substr($string, 4);
# Printing the substring
print "Substring 1 : $sub_string1\n";
# Calling substr() to find the
# substring of a fixed length
$sub_string2 = substr($string, 4, 5);
# Printing the substring
print "Substring 2 : $sub_string2 ";
输出 :
Substring 1 : sForGeeks
Substring 2 : sForG
示例 2
#!/usr/bin/perl
# String to be passed
$string = "GeeksForGeeks";
# Calling substr() to find string
# by passing negative index
$sub_string1 = substr($string, -4);
# Printing the substring
print "Substring 1 : $sub_string1\n";
# Calling substr() to find the
# substring by passing negative length
$sub_string2 = substr($string, 4, -2);
# Printing the substring
print "Substring 2 : $sub_string2 ";
输出 :
Substring 1 : eeks
Substring 2 : sForGee