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
I love the readability of this tip!
One suggestion is to use the "first" sub from List::Util to speed things up.
Thanks for the suggestion silevitch.
List::Util looks useful though I don't use too many CPAN modules yet (mainly because of the authorization required to work with them). I try the installed modules or the Pure Perl modules. The modules I have tried are: DBI/DBD, CSV_PP (pure perl version of CSV_XS), XML::Simple, XML::LibXML, POSIX and a few other standard modules.
Perl Squirrel
List::Util is part of core. Should be already installed and ready for you to use.