Skip to content
Related Articles

Related Articles

Perl | grep() Function
  • Last Updated : 07 May, 2019
GeeksforGeeks - Summer Carnival Banner

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

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.

My Personal Notes arrow_drop_up
Recommended Articles
Page :