Perl Array Grep() Function

Using the Array Grep() Function to Filter Array Elements

Engineer working in an office

Aping Vision/STS/Photodisc/Getty Images

The Perl grep() function is a filter that runs a regular expression on each element of an array and returns only the elements that evaluate as true. Using regular expressions can be extremely powerful and complex. The grep() functions uses the syntax @List = grep(Expression, @array).

Using Grep() Function to Return True Expressions

@myNames = ('Jacob', 'Michael', 'Joshua', 'Mathew', 'Alexander', 'Andrew');
@grepNames = grep(/^A/, @myNames);

Think of the @myNames array as a row of numbered boxes, going from left to right and numbered starting with a zero. The grep() function goes through each of the elements (boxes) in the array and compares their contents to the regular expression. If the result is true, the contents are then added to the new @grepNames array.

In the above example, the regular expression /^A/ is looking for any value that starts with a capital A. After sifting through the contents of the @myNames array, the value of @grepNames becomes ('Alexander', 'Andrew'), the only two elements that start with a capital A.

Reversing the Expression in a Grep() Function

One quick way to make this particular function more powerful is to reverse the regular expression with the NOT operator. The regular expression then looks for elements that evaluate to false and moves them into the new array.

@myNames = ('Jacob', 'Michael', 'Joshua', 'Mathew', 'Alexander', 'Andrew');
@grepNames = grep(!/^A/, @myNames);

In the above example, the regular expression is looking for any value that does not start with a capital A. After sifting through the contents of the @myNames array, the value of @grepNames becomes ('Jacob', 'Michael', 'Joshua', 'Matthew').

About Perl

Perl is an adaptable programming language frequently used to develop web applications. Perl is an interpreted, not compiled, language, so its programs take up more CPU time than a compiled language—a problem that becomes less important as the speed of processors increases. However, writing in Perl is faster than writing in a compiled language, so the time you save is yours. 

Format
mla apa chicago
Your Citation
Brown, Kirk. "Perl Array Grep() Function." ThoughtCo, Aug. 26, 2020, thoughtco.com/perl-array-grep-function-quick-tutorial-2641158. Brown, Kirk. (2020, August 26). Perl Array Grep() Function. Retrieved from https://www.thoughtco.com/perl-array-grep-function-quick-tutorial-2641158 Brown, Kirk. "Perl Array Grep() Function." ThoughtCo. https://www.thoughtco.com/perl-array-grep-function-quick-tutorial-2641158 (accessed April 16, 2024).