Perl's grep is inspired by the Unix / Linux command grep

Perl has a function called grep, which is inspired by Perl's grep from the Unix / Linux command grep.

Unix / Linux command grep

The basic function of grep in Unix / Linux commands is to search for a string in a file and retrieve and display the corresponding line, if any.

grep cake food.txt

If there is a line in footd.txt that contains the cake, it will be displayed.

Perl's grep function

Perl's grep function is inspired by the Unix / Linux command grep.

The function of Perl's grep function is to retrieve all the elements of an array that meet the conditions.

Whereas the grep command targets each line in the file, Perl's grep function is an element of the array.

Let's write a sample of the grep function. This is a sample to extract only even numbers.

# Extract only even numbers with grep function
my @nums = (1, 2, 3, 4);
my @even_nums = grep {$_%2 == 0} @nums;

Each element of the array comes in the default variable "$_". And only those that match the even condition will return the new fetched array.

Perl's grep function is very similar to Unix / Linux's grep command.

Perl regular expressions can also be used with the grep command

Perl regular expressions are practical regular expressions that implement features that make it easy to solve common problems.

Although experimental, in modern Linux you can also use Perl regular expressions with the grep command using the "-P" option.

grep -P'(\ .txt | \ .html) $'food.txt

Perl's regular expressions, which have become popular and widely used in Perl, can also be used on the grep command side.

Associated Information