Perl Grep



Perl 5 has a linux shell like 'grep' function that can be used to filter a list based on certain criteria. Just link linux "grep" is used to find list of files based on certain criteria which is specified as regex (or regular expression) or simply text, "perl grep" can be used to filter list and return elements that match the criteria.

Perl Grep would return the sublist that is filter of original list. In this tutorial, we cover examples of "Perl Grep" function and how it is used in Perl script:

Perl grep Syntax:

grep BLOCK LIST
grep (EXPR, LIST)

Example of above syntax where both are equivalent is below and both remove comments that start with #:

@foo = grep(!/^#/, @bar);
@foo = grep {!/^#/} @bar; 

Lets look at the example to understand better how perl grep is used:

Perl Grep: Example 1

#!/usr/bin/perl
 
use strict;
use warnings;
 
# initialize array
my @words =('Kernighan', 'Ritchie', 'Piker');
 
my $count = grep /er$/, @words;
 
print "\$count\n"; 

This would output 1. Since, only Piker is the word ending with "er". We have written a perl based regular expression inside grep which means all words ending with er. Fun!

Did you notice the perl grep function is returning the count and not the subset? When grep is used in scalar context, it would return the count the EXPR is evaluated TRUE.

Lets look at another example:

Perl Grep: Example 2

#!/usr/bin/perl
 
use strict;
use warnings;
 
# initialize array
my @words =('Kernighan', 'Ritchie', 'Piker');
 
my @subArray= grep /er$/, @words;
 
print "@subArray\n";

This would output

Piker

Since, only the 3rd item in the array words returns TRUE with perl grep function and we want to select only those items that return TRUE.