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:



filter_none

edit
close

play_arrow

link
brightness_4
code

#!/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;

chevron_right



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:

filter_none

edit
close

play_arrow

link
brightness_4
code

#!/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;

chevron_right


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:

filter_none

edit
close

play_arrow

link
brightness_4
code

#!/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;

chevron_right


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’.




My Personal Notes arrow_drop_up

Image
Check out this Author's contributed articles.

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.