Ternary operators alternatives - Perl and Lua lazy operators
Archive - Originally posted on "The Horse's Mouth" - 2009-08-12 07:27:14 - Graham Ellis"If the gender is male, the answer is him, but if the gender is female, the answer is her". A common situation in programming - [is/are], [him/her], [yes/no], [child/children], [ice/water/steam], [public/private] - and C and Perl and PHP provide the "ternary" operator ? and : to provide a shorthand alternative to a code-heavy if/else structure:
$thing = ($stock == 1) ? "item" : "items";
(That's PHP and Perl to set the "thing" variable to item (singular) or items (plural) depending on the value of $stock being equal (or not) to 1.
In Perl, there's always half a dozen ways to do anything, and the same effect can be created using the lazy and and or keywords ... the logic goes something like this:
i) "If both a and b need to be true and we have already discovered that a is false, we don't need to bother to do test b. And indeed to do test b would be inefficient in such a circumstance. Since (a) is a false value, we'll just return that
ii) "If either a or b needs to be true, and we have already discovered that a is true we don't need to bother to do test b. And indeed to do test b would be inefficient in such a circumstance. Since (a) is a true value, we'll just return that
iii) If we have to move on to test the second item in any circumstance, we may as well just return the value of that item as it's going to be a true value if the whole result is true, and a false value if the whole result is false.
Let's see that in action ... here in Perl:
[trainee@easterton a9_2]$ perl
print (16 and 35)
35[trainee@easterton a9_2]$ perl
print (16 or 35)
16[trainee@easterton a9_2]$
So the result is 16 or 35. By extending that to use both and and or, you'll find that you have a very convenient (and I'm sure planned when the language was written) shorthand for if - else:
[trainee@easterton a9_2]$ perl
print (1 and 4 or 9)
4[trainee@easterton a9_2]$ perl
print (0 and 4 or 9)
9[trainee@easterton a9_2]$
The same thing applies (or rather - ALMOST the same thing) in Lua - where it is especially useful as the language does NOT support the ternary operator:
[trainee@easterton a9_2]$ lua
Lua 5.1.4 Copyright (C) 1994-2008 Lua.org, PUC-Rio
> print (1 and 4 or 9)
4
> print (0 and 4 or 9)
4
> print ( false and 4 or 9)
9
>
I say "almost" the same, because in Lua, the number 0 is a true value, as is an empty string. Only the boolean false, and nil, are really false values. And that's ideal in most circumstances, where you want to be able to accept 0 as just another number - indeed, in Perl 6 you'll be able to say that a number is "0 but true" which rather acknowledges the need for a revision of the "0 is false" mantra.