ZetCode

Perl grep

last modified November 25, 2026 Perl 5.44

The grep function filters a list. It evaluates a block or an expression for each element and returns the elements for which the result is true. Inside the block, the current element is available as $_. The name comes from the Unix grep command, but Perl's function can test any condition, not only a regular expression.

Filtering a list with a block

The most common form of grep takes a block and a list. The block is a condition, and the elements that satisfy it end up in the result.

negatives.pl
#!/usr/bin/perl

use warnings;
use v5.34.0;

my @vals = (-3, -1, 0, 3, -4, 2, 3, 4, -7);

my @neg = grep { $_ < 0 } @vals;

say "values:   @vals";
say "negative: @neg";

The block { $_ < 0 } is evaluated once for every number. The negative numbers are returned in their original order. The original array is not changed.

$ perl negatives.pl
values:   -3 -1 0 3 -4 2 3 4 -7
negative: -3 -1 -4 -7

Counting matches

In scalar context, grep does not return the elements but the number of elements that passed the test.

count.pl
#!/usr/bin/perl

use warnings;
use v5.34.0;

my @vals = (-3, -1, 0, 3, -4, 2, 3, 4, -7);

my $n = grep { $_ < 0 } @vals;
say "there are $n negative values";

if (grep { $_ == 0 } @vals) {
    say "the list contains a zero";
}

Assigning to the scalar $n puts grep in scalar context, so we get a count. An if condition is scalar context too. A count of zero is false, so the condition is true when at least one element is zero.

$ perl count.pl
there are 4 negative values
the list contains a zero

The expression form and regular expressions

Instead of a block, grep accepts a single expression followed by a comma. This form is common with regular expressions, because a bare /pattern/ matches against $_.

regex.pl
#!/usr/bin/perl

use warnings;
use v5.34.0;

my @words = qw(sky war cup cloud abyss water car book note falcon);

my @wc = grep /^[wc]/, @words;
say "start with w or c: @wc";

my @three = grep { length == 3 } @words;
say "three letters:     @three";

my @no_vowel = grep !/[aeiou]/, @words;
say "no a/e/i/o/u:      @no_vowel";

The first call keeps words that start with w or c. The second one uses a block, in which length without an argument measures $_. The ! operator negates a match, so the third call keeps words without any of the listed vowels. Note the comma after the expression form, and no comma after a block.

$ perl regex.pl
start with w or c: war cup cloud water car
three letters:     sky war cup car
no a/e/i/o/u:      sky

Combining conditions

A block can contain any code, and its last expression decides whether the element is kept. Several conditions are combined with && and ||.

conditions.pl
#!/usr/bin/perl

use warnings;
use v5.34.0;

my @lines = (
    '# configuration',
    'host = example.com',
    '',
    'port = 8080',
    '   ',
    '# debug = 1',
    'user = lucia',
);

my @settings = grep { /\S/ && !/^\s*#/ } @lines;

say for @settings;
say scalar(@settings), " of ", scalar(@lines), " lines are settings";

The lines resemble a configuration file. The /\S/ test drops empty lines and lines with only spaces, because they contain no non-whitespace character. The !/^\s*#/ test drops comments. Only the three real settings remain.

$ perl conditions.pl
host = example.com
port = 8080
user = lucia
3 of 7 lines are settings

Removing duplicates

The block can also keep state between elements in an outer variable. A well-known idiom uses a hash to remember the elements already seen and returns each value only once.

unique.pl
#!/usr/bin/perl

use warnings;
use v5.34.0;

my @tags = qw(perl web perl db web perl cli);

my %seen;
my @unique = grep { !$seen{$_}++ } @tags;

say "tags:   @tags";
say "unique: @unique";

for my $tag (@unique) {
    say "$tag: $seen{$tag}";
}

$seen{$_}++ returns the old count and then increments it. For the first occurrence of a tag, the old count is undefined, so !$seen{$_}++ is true and the tag is kept. Later occurrences have a positive count and are dropped. When grep is done, the hash holds the number of occurrences of every tag. Since Perl 5.26, the core List::Util module also offers a uniq function.

$ perl unique.pl
tags:   perl web perl db web perl cli
unique: perl web db cli
perl: 3
web: 2
db: 1
cli: 1

Filtering hashes

A hash cannot be passed to grep as pairs, but its keys can. The block then looks up the value for each key.

hash_filter.pl
#!/usr/bin/perl

use warnings;
use v5.34.0;

my %stock = (
    apples   => 12,
    bananas  => 0,
    cherries => 150,
    dates    => 3,
    figs     => 0,
);

my @sold_out = grep { $stock{$_} == 0 } sort keys %stock;
say "sold out: @sold_out";

my @low = grep { $stock{$_} > 0 && $stock{$_} < 10 } sort keys %stock;
say "running low: @low";

my %available = %stock{ grep { $stock{$_} > 0 } keys %stock };

for my $fruit (sort keys %available) {
    say "$fruit: $available{$fruit}";
}

The keys are sorted first, so the results come in a predictable order. The first two calls select keys by their values. The last one builds a new hash. The expression %stock{...} is a key/value slice. It returns the listed keys together with their values, which is exactly what a hash assignment needs.

$ perl hash_filter.pl
sold out: bananas figs
running low: dates
apples: 12
cherries: 150
dates: 3

Filtering records

Real data often comes as an array of hash references, one hash per record. In the block, $_ is a reference, and the fields are reached with the arrow operator.

records.pl
#!/usr/bin/perl

use warnings;
use v5.34.0;

my @products = (
    { name => 'keyboard', price => 45,  tags => ['usb', 'input'] },
    { name => 'monitor',  price => 220, tags => ['hdmi', 'display'] },
    { name => 'mouse',    price => 25,  tags => ['usb', 'input'] },
    { name => 'webcam',   price => 60,  tags => ['usb', 'video'] },
    { name => 'speakers', price => 80,  tags => ['audio'] },
);

my @cheap = grep { $_->{price} < 50 } @products;
say "under 50: $_->{name}" for @cheap;

my @usb = grep {
    my $p = $_;
    grep { $_ eq 'usb' } @{ $p->{tags} };
} @products;
say "usb:      $_->{name}" for @usb;

The first call keeps the products cheaper than 50. The second one has a nested grep, which searches the tags of a product. The inner block has its own $_, so the product is saved in $p first. In the outer block, the inner grep is in scalar context and returns the number of matching tags. References are covered in Perl references.

$ perl records.pl
under 50: keyboard
under 50: mouse
usb:      keyboard
usb:      mouse
usb:      webcam

Finding indexes

Sometimes we need the positions of the matching elements rather than the elements themselves. In that case, grep filters the list of indexes.

indexes.pl
#!/usr/bin/perl

use warnings;
use v5.34.0;

my @temps = (3, -2, 5, -7, 0, 4, -1);

my @idx = grep { $temps[$_] < 0 } 0 .. $#temps;
say "frost on days: @idx";

my ($first) = grep { $temps[$_] < 0 } 0 .. $#temps;
say "first frost on day $first";

for my $i (@idx) {
    say "day $i: $temps[$i] degrees";
}

The range 0 .. $#temps produces all valid indexes of the array. The block tests the element at each index, and the indexes of negative temperatures are returned. Assigning to a list with one variable, my ($first), keeps the first index. The other indexes are discarded.

$ perl indexes.pl
frost on days: 1 3 6
first frost on day 1
day 1: -2 degrees
day 3: -7 degrees
day 6: -1 degrees

Stopping early with List::Util

grep always walks through the whole list. To find a single element or to check whether some element matches, the core List::Util module has functions that stop at the first decisive element.

list_util.pl
#!/usr/bin/perl

use warnings;
use v5.34.0;
use List::Util qw(first any all none);

my @temps = (3, -2, 5, -7, 0, 4, -1);

my $first_neg = first { $_ < 0 } @temps;
say "first negative value: $first_neg";

say "some day below zero" if any  { $_ < 0 } @temps;
say "all days below ten"  if all  { $_ < 10 } @temps;
say "no day above 30"     if none { $_ > 30 } @temps;

my $checked = 0;
my $found = any { $checked++; $_ < 0 } @temps;
say "any stopped after $checked elements";

$checked = 0;
my $n = grep { $checked++; $_ < 0 } @temps;
say "grep checked all $checked elements";

first returns the first element that passes the test. any, all and none return true or false. The counters show the difference: any stops at the second element, the first negative one, while grep checks all seven. For long lists or expensive tests, this matters.

$ perl list_util.pl
first negative value: -2
some day below zero
all days below ten
no day above 30
any stopped after 2 elements
grep checked all 7 elements

$_ is an alias

Inside the block, $_ is not a copy of the element but an alias to it. Code that modifies $_ modifies the original array, which is a common source of bugs.

aliasing.pl
#!/usr/bin/perl

use warnings;
use v5.34.0;

my @names = ('  alice', 'bob  ', ' carol ');

my @with_o = grep { s/^\s+|\s+$//g; /o/ } @names;
say "matched:  ", join '|', @with_o;
say "original: ", join '|', @names;

my @raw = ('  dave', 'eve  ', ' frank ');

my @with_a = grep { s/^\s+|\s+$//gr =~ /a/ } @raw;
say "matched:  ", join '|', @with_a;
say "original: ", join '|', @raw;

The first grep trims the names with a substitution before matching. The substitution changes $_, and with it every element of @names. The second grep uses the /r modifier, which returns a modified copy and leaves $_ alone. The original array stays unchanged, and grep returns the original, untrimmed elements. To transform elements, use map instead.

$ perl aliasing.pl
matched:  bob|carol
original: alice|bob|carol
matched:    dave| frank 
original:   dave|eve  | frank 

Best practices

These recommendations help to use grep clearly.

Source

grep ยท List::Util

In this article we have filtered lists, counted matches, combined conditions, removed duplicates, filtered hashes and records, found indexes, stopped early with List::Util and seen why $_ must not be modified. See also Perl map, Perl sort and Perl array.

Author

I am Jan Bodnar, a programmer and technical writer. I have been writing programming tutorials at ZetCode since 2007 and have published eight e-books. See about the author.

List all Perl tutorials.