Search #3

#0 | #1 | #2 | #3

grep

grep is a Perl function which performs a similar 'function' as the grep utility that comes with most Linux and Unix systems.

The term stands for global regular expression and print. The Perl version of grep is also used to search for items in a list, but is considered a 'loop' construct, like map.

It's considered a loop construct, since it is best used in that situation.

It is considered Best Practice not to call 'grep' in a void context.

Meaning, you should always assign a variable to its results, or at least don't just throw them away.

For example, a typical situation is looking through an array, and building another array out of items that match a certain criteria:

@a = (1 .. 20);
foreach (@a) {
    if ($_ > 11) {
        push @b,$_;
    }
};
print join(", ",@b);

Which will print 12, 13, 14, 15, 16, 17, 18, 19, 20

But, if we write that loop using grep it becomes a bit shorter, and easier to implement:

@a = (1 .. 20);
@b = grep ($_ > 11);
print join(", ",@b);

Not surprisingly, it prints exactly the same thing: 12, 13, 14, 15, 16, 17, 18, 19, 20.

Here's another example, removing 4-letter words from a string:

print (join" ",(grep {!/^\w{4}$/} ( qw (Here be some four letter words.))));

If you trust my code, it will print out: be letter words.

Actually whether you trust my code or not, it still prints that.

The block of code (regular expression) used by grep in this case has 1 new bit of wisdom for you:

\w{4} stands for a word \w
4 characters long {4}.

The rest of the expression should be familiar from previous pages.