Open In App

Perl | grep() Function

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Share
Report issue
Report

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
 
# 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: 

Perl




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

Perl




#!/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’.



Last Updated : 20 Jun, 2022
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads