Question Mark - Colon operator (Perl and PHP)
Archive - Originally posted on "The Horse's Mouth" - 2008-10-08 07:21:47 - Graham EllisThe ? and : operator in Perl and PHP allows you to write a single statement that's both an if and an else without the need for all the clutter of keywords, extra variables, and so on if all you want to do is come up with two alternative words.
Here's an example in PHP - throwing a number on a die, and telling the user to proceed if the value thrown is a five or six, but to try again is it's a 1, 2, 3 or 4:
<?php
# Throw a die
$throw = rand(1,6);
print ("You threw a $throw which means you should ".
(($throw > 4) ? "proceed" : "try again").
" at the next turn\n");
?>
Here's how it works ("all our code is tested" as I wrote in an email to someone yesterday!)
Dorothy:p1 grahamellis$ php pz
You threw a 3 which means you should try again at the next turn
Dorothy:p1 grahamellis$ php pz
You threw a 6 which means you should proceed at the next turn
Dorothy:p1 grahamellis$
Here is the same functionallity using if and else:
<?php
# Throw a die
$throw = rand(1,6);
if ($throw > 4) {
$action = "proceed";
} else {
$action = "try again";
}
print ("You threw a $throw which means you should ".
"$action at the next turn\n");
?>
In Perl (I'm running a Learning to Program in Perl course this week, which is where this article originated!), you have the same thing - and a wide variety of other convenient alternatives to if for conditionals and while for loops. I've posted up an example that uses until and also the ? : pairing at http://www.wellho.net/resources/ex.php4?item=p206/golf ... in this demonstration, you enter the number of individuals or teams you have signed up for a knock out competition, and the program tells you what your target should be if you want a perfect knockout with no need for any "byes" in the first round. Here it is running:
Dorothy:p1 grahamellis$ perl golf
How many people? 6
You really need 8
Dorothy:p1 grahamellis$ perl golf
How many people? 8
You're fine as you are with 8
Dorothy:p1 grahamellis$ perl golf
How many people? 11
You really need 16
Dorothy:p1 grahamellis$
You'll note - once again - the subtle use of ? : in the code to change the text "you'll really need ..." into "you're fine as you are with ..." - oh the power of Perl and its plethora of operators.