Monday, November 30, 2009

Perl - A compact multiple-value IF statement using grep

Here is a simple way to compare multiple string values against a variable.
Normally one might use multiple OR conditions such as:

$pet = "rabbit";
if ( uc($pet) eq "CAT" || 
     uc($pet) eq "DOG" ||
     uc($pet) eq "HAMSTER" ||
     uc($pet) eq "RABBIT" ||
     uc($pet) eq "RACCOON" ||
     uc($pet) eq "MONKEY" ||
     uc($pet) eq "HORSE" ) {
     printf("A %s is a Mammal.\n", ucfirst($pet) );
}
elsif ( uc($pet) eq "ALLIGATOR" ||
        uc($pet) eq "FROG" ||
        uc($pet) eq "SALAMANDER" ||
        uc($pet) eq "SNAKE" ||
        uc($pet) eq "TOAD" ) {
    printf("A %s is an Amphibian.\n", ucfirst($pet) );
}
else {
    printf("What is a %s ?\n", ucfirst($pet) );
}


Here is an easier way (Full string match, not case-sensitive):

#Search word
$pet = "rabbit";

#Regular Expression: / ^=beginning of string, $pet variable, $=end of string / i=ignore case
#Using Anonomous 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) );
}


Some notes:
  • Removing the "i" option would make the statement case-sensitive:
  • Altering the Regular Expression slightly, will match the beginning or end of strings.
    Matching the beginning of the strings (remove the ending $ symbol):
    Matching the end of the strings (remove the leading ^ carret symbol):