The grep() function in Perl used to extract any element from the given array which evaluates the true value for the given regular expression.
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 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.
Example 1:
Perl
#!/usr/bin/perl
@Array = ( 'Geeks' , 'for' , 'Geek' );
@A = grep (/^G/, @Array );
print @A ;
|
Output:
GeeksGeek
In the above code, Regular expression /^G/ is used to get the element starting with ‘G’ from the given array and discard the remaining elements. Example 2:
Perl
#!/usr/bin/perl
@Array = ( 'Geeks' , 1, 2, 'Geek' , 3, 'For' );
@A = grep (/\d/, @Array );
print @A ;
|
Output :
123
In the above code, Regular expression /^d/ is used to get the integer value from the given array and discard the remaining elements.
Example 3:
Perl
#!/usr/bin/perl
@Array = ( 'Ram' , 'Shyam' , 'Rahim' , 'Geeta' , 'Sheeta' );
@A = grep (!/^R/, @Array );
print @A ;
|
Output :
ShyamGeetaSheeta
In the above code, Regular expression !/^R/ is used to get the elements not starting with ‘R’ and discard the elements which start with ‘R’.
Last Updated :
20 Jun, 2022
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...