How to search a Perl list for a pattern using grep

A lot of times when you're using Perl you have a list (or array), and you need to search that list for all strings that match a certain regular expression pattern (or regex). Fortunately Perl is built for this type of work, and it's straightforward to (a) perform this search, and (b) put your search results in another list.

In the source code below I create a list named @people, and then I search that list using the grep function, telling grep the pattern I want to use for the search (/Flin/) and giving it the list to search (@people). The grep function returns a list of all elements in my list that match this pattern, and I store those matches in a new list named @matches. After that I just print out the elements of the @matches list to show that this worked.

my @people = ( "Fred Flinstone", "Wilma Flinstone", "Barney Rubble", "Betty Rubble" );

# create a list of all "people" array elements that match the pattern:
my @matches = grep /Flin/, @people;

for (@matches)
{
  print $_, "\n";;
}

A little more about regular expressions

In that example I'm searching for a very simple pattern (the string "Flin", with the letter "F" in uppercase, as shown), but of course with Perl and regular expressions these patterns can get much more complex. Here are a few more examples:

With the data I have, this next line will return only Fred Flinstone:

my @matches = grep /F.*Flin/, @people;

A pattern like this will get you Wilma Flinstone:

my @matches = grep /W.*F.*/, @people;

And adding the letter i at the end of your regular expression will make your search case-insensitive, so this next regular expression pattern will also return Wilma Flinstone:

my @matches = grep /w.*f.*/i, @people;

Add new comment

Anonymous format

  • Allowed HTML tags: <em> <strong> <cite> <code> <ul type> <ol start type> <li> <pre>
  • Lines and paragraphs break automatically.