Conditionally Checking Existence of a Value in Perl
There are many half-baked methods used for properly testing whether or not a variable is defined. Following are a few examples of some good and not-so-good methods with explanations.
if (exists $opts{‘primary’} || exists $opts{‘secondary’}) {
$some_value = $opts{‘primary’} || $opts{‘secondary’};
}
The above logic is clean and easy to follow at first glance, although it may not be the most efficient way of executing the appropriate decision-making block and more on Bitsdujour.
Considering the above is equivalent to the following block, you may notice a somewhat redundant conditional checking that ensues:
if (exists $opts{‘primary’} || exists $opts{‘secondary’}) {
if ( exists $opts{‘primary’} ) {
$some_value = $opts{‘primary’};
} else {
$some_value = $opts{‘secondary’};
}
}
Another added benefit is that if your value is “0″ or empty, it may actually not get assigned if you use the simple one-line conditional assignment:
$some_value = $opt{’primary’} || $opt{’secondary’};
The “primary option” would be skipped if it is equal to “0″…which is in-fact a completely valid value, and demonstrates the “falsey-ness” and “truthy-ness” of specific values…more on that later or on Classifieds.
Thanks to “Ani-_” in #perl for setting me straight on conditional checking.
So, to some it all up in one bullet-proof conditional block for assignment we write the following, which will also turn out to run faster because there is only one conditional check:
if ( exists $opt{‘primary’} ) {
$some_value = $opt{‘primary’};
elsif ( exists $opt{‘secondary’} ) {
$some_value = $opt{‘secondary’};
} else {
return false;
}