Perl

  1. Home
  2. Computing & Technology
  3. Perl

Perl array grep() function - Quick Tutorial

How to use the array grep() function

From About.com

@LIST = grep(EXPRESSION, @ARRAY);
Perl's grep() function runs a regular expression on each element of an array, and returns only the elements that evaluate to true. Using regular expressions can be extremely powerful and complex. You can find out more about them in the regular expressions topic.
@myNames = ('Jacob', 'Michael', 'Joshua', 'Matthew', 'Alexander', 'Andrew');
@grepNames = grep(/^A/, @myNames);
Think of the @myNames array as a row of numbered boxes, going from left to right, 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 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').

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', 'Matthew', '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').

More Perl Quick Tips

Explore Perl

About.com Special Features

Build Your Own Website

Step-by-step advice on how to do everything from choosing a Web host to promoting your content. More >

Connect Your Home Computers

Easy ways to connect two computers for networking purposes. More >

Perl

  1. Home
  2. Computing & Technology
  3. Perl
  4. Programming Perl
  5. Perl grep function reference - learn how to use Perl's grep() function in this quick tutorial.

©2009 About.com, a part of The New York Times Company.

All rights reserved.