Perl grep array FAQ - How to search an array/list of strings

Perl "grep array" FAQ: Can you demonstrate a Perl grep array example? (Related: Can you demonstrate how to search a Perl array?)

A very cool thing about Perl is that you can search lists (arrays) with the Perl grep function. This makes it very easy to find things in large lists -- without having to write your own Perl for/foreach loops.

A simple Perl grep array example (Perl array search)

Here's a simple Perl array grep example. First I create a small string array (pizza toppings), and then search the Perl array for the string "pepper":

# create a perl list/array of strings
@pizzas = qw(cheese pepperoni veggie sausage spinach garlic);

# use the perl grep function to search the @pizzas list for the string "pepper"
@results = grep /pepper/, @pizzas;

# print the results
print "@results\n";

As you might guess from looking at the code, my @results Perl array prints the following output:


Perl grep array - case-insensitive searching

If you're familiar with Perl regular expressions, you might also guess that it's very easy to make this Perl array search example case-insensitive using the standard i operator at the end of my search string.

Here's what our Perl grep array example looks like with this change:

@results = grep /pepper/i, @pizzas;

Perl grep array and regular expressions (regex)

You can also use more complex Perl regular expressions (regex) in your array search. For instance, if for some reason you wanted to find all strings in your array that contain at least eight consecutive word characters, you could use this search pattern:

@results = grep /\w{8}/, @pizzas;

That example results in the following output:


Perl grep array - Summary

I hope this Perl grep array example (Perl array search example) has been helpful. For related Perl examples, see the Related block on this web page, or use the search form on this website. If you have any questions, or better yet, more Perl array search examples, feel free to use the Comments section below.