How to write a multiple value if statement using Perl grep

Here is a compact way of writing a multi-value if statement.
Lets say you have a scalar string variable and need to see if it matches a number of possible values.
You want it not case-sensitive and the comparisons must match exactly.

Source code:

#Search word
$pet = "rabbit";

#Regular Expression: / ^=beginning of string, $pet variable, $=end of string / i=ignore case
#Using Anonymous Array: ("cat", "dog", "...as-many-as-you-like...", "horse")
if ( grep /^$pet$/i, ("cat","dog","hamster","RABBIT","Raccoon","Monkey","horse") ) {
printf("A %s is a Mammal.\n", ucfirst($pet) );
}
elsif ( grep /^$pet$/i, ("Alligator", "frog", "salamander", "Snake", "toad") ) {
printf("A %s is an Amphibian.\n", ucfirst($pet) );
}
else {
printf("What is a %s ?\n", ucfirst($pet) );
}
#- - - end - - -

Notes:


  • Removing the "i" option from the grep would make the statement case-sensitive

  • Removing the ending $ symbol from the grep would make it a starts-with search

  • Removing the beginning ^ symbol from the grep would make it a ends-with search

  • Removing both the beginning ^ symbol and the ending $ symbol would make it a match any part of the string comparison

  • The convenient thing about using this "if and grep" combo is for testing for multiple string values such as "Yes","yes","yeS","you-betcha","OK","ok","Ok","you-got-it".

  • Put a named array in-place of a hard-coded anonymous array and you'll have quite an if-statement!
  • Enjoy,
    Perl Squirrel

3 Comments

I love the readability of this tip!

One suggestion is to use the "first" sub from List::Util to speed things up.

List::Util is part of core. Should be already installed and ready for you to use.

Leave a comment

About Perl Squirrel

user-pic I am a UNIX developer with an interest in Perl, UNIX shell scripting, database application development. Tools used: Perl, KSH, UNIX / Linux, Putty, DB2, Oracle, XML, Awk, and others. I blog about Perl.