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 | Basic Syntax of a Perl Program
- Perl Tutorial - Learn Perl With Examples
- Perl | split() Function
- Perl | chomp() Function
- Perl | chop() Function
- Perl | rename() Function
- Perl | undef and the defined function
- Perl | cos() Function
- Perl | sin() Function
- Perl | abs() function
- Perl | atan2() Function
- Perl | splice() - The Versatile Function
- Perl | delete() Function
- Perl | defined() Function
- Perl | each() Function
- Perl | index() Function
- Perl | int() function
- Perl | join() Function
- Perl | keys() Function
- Perl | lc() Function for Lower Case Conversion
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.

