"Perl for Perl Newbies" - Part 2Useful Functionsgrep

9.4. grep

The grep function can be used to filter items out of an array based on a boolean expression or a regular expression. The syntax for the block usage is similar to map while the syntax for the regexp usage is similar to split.

Here is an example that takes a file and filters only the perl comments whose length is lesser than 80 characters:

use strict;
use warnings;

my (@lines, $l);

my $filename = shift;

open my $in, "<", $filename;
while ($l = <$in>)
{
    chomp($l);
    push @lines, $l;
}
close($in);

# Filter the comments
my @comments = grep(/^#/, @lines);
# Filter out the long comments
my @short_comments = (grep { length($_) <= 80 ; } @comments);

print join("\n", @short_comments), "\n";

And here's how grep can help us find the first 100 primes:

use strict;
use warnings;

my @primes = (2);
for(my $n=3 ; scalar(@primes) < 100 ; $n++)
{
    if (scalar(grep { $n % $_ == 0 ; } @primes) == 0)
    {
        push @primes, $n;
    }
}
print join(", ", @primes), "\n";

Written by Shlomi Fish