珀尔 | grep()函数
Perl 中的 grep()函数用于从给定数组中提取任何元素,该数组计算给定正则表达式的真值。
Syntax: grep(Expression, @Array)
Parameters:
- Expression : It is the regular expression which is used to run on each elements of the given array.
- @Array : It is the the given array on which grep() function is called.
Returns: any element from the given array which evaluates the true value for the given regular expression.
示例 1:
#!/usr/bin/perl
# Initialising an array of some elements
@Array = ('Geeks', 'for', 'Geek');
# Calling the grep() function
@A = grep(/^G/, @Array);
# Printing the required elements of the array
print @A;
输出:
GeeksGeek
在上面的代码中,正则表达式/^G/用于从给定的数组中获取以 'G' 开头的元素并丢弃剩余的元素。
示例 2:
#!/usr/bin/perl
# Initialising an array of some elements
@Array = ('Geeks', 1, 2, 'Geek', 3, 'For');
# Calling the grep() function
@A = grep(/\d/, @Array);
# Printing the required elements of the array
print @A;
输出 :
123
在上面的代码中,正则表达式/^d/用于从给定的数组中获取整数值并丢弃剩余的元素。
示例 3:
#!/usr/bin/perl
# Initialising an array of some elements
@Array = ('Ram', 'Shyam', 'Rahim', 'Geeta', 'Sheeta');
# Calling the grep() function
@A = grep(!/^R/, @Array);
# Printing the required elements of the array
print @A;
输出 :
ShyamGeetaSheeta
在上面的代码中,正则表达式!/^R/用于获取不以'R'开头的元素并丢弃以'R'开头的元素。