Perl | grep() Function
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 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:
#!/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; |
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:
#!/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; |
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:
#!/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; |
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’.
Recommended Posts:
- Perl | ord() Function
- Perl | int() function
- Perl | tell() Function
- Perl | log() Function
- Perl | oct() Function
- Perl | each() Function
- Perl | abs() function
- Perl | chr() Function
- Perl | cos() Function
- Perl | sin() Function
- Perl | uc() Function
- Perl | hex Function
- Perl | exp Function
- Perl | reset() Function
- Perl | index() Function
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



