Perl - How to compare a string against multiple patterns

For a Perl program that I'm working on right now, I need to match the elements of an array of strings against several patterns, and then take an action if the current string matches one of my patterns. This is pretty easy in this case, in part because it's easy to match a string against multiple patterns in Perl, and also because my patterns are very simple -- no regular expressions involved.

The Perl source code below shows a simple example of the pattern matching that I'm doing in my Perl script. In this sample program I have a method named print_filter that prints lines that only match specific, simple patterns. In this case I only print the strings that contain the patterns print, allow, or okay. These patterns can be anywhere in the string that is passed in, but they must be in lower case.

Here's the sample code:

#!/usr/bin/perl

sub print_filter
{
  my $string = shift;
  #
  # here's where the filtering happens
  #
  return unless ($string =~ m/(print|allow|okay)/);
  print "$string\n";
}

&print_filter("print this one");
&print_filter("allow this one");
&print_filter("this one is okay");
&print_filter("don't do this one");

As you can see I call the print_filter method four times, passing in different strings. The only lines that are printed are those that match the three patterns I'm performing a comparison against: print, allow, and okay. The output looks like this:

print this one
allow this one
this one is okay

A shorter way to write the comparison

There's actually a shorter way to write that return unless line of code, but I didn't want to throw it at you all at once. Here's how you can simplify that line of code:

return unless $string =~ /print|allow|okay/;

When you're performing a simple pattern match like this you can use this format, without the leading m character or the parentheses. I think this format is a little easier to read, and as a final note, you'll see this syntax used more commonly in Perl programs than the first syntax I showed.

Comments

Permalink

seems easier to express that logic as:

print $string if $string =~ m/print|allow|okay/;

think positive if possible :-)