Main Content

A short form of if ... then ... else

Archive - Originally posted on "The Horse's Mouth" - 2009-10-23 07:26:25 - Graham Ellis

There are so many times you want to say "if ... then ... else" to do no more than choose between the word "is" and "are", to say "child" or "children", or to say "may" or "may not" in your output. Using an if statement for that's a lot of code for a little job.

In most of the languages we teach (Perl, PHP, Python, Java, Ruby and C and C++), the ? ... : operator allows you to do a 'rapid fire' If and else ...

PHP, Perl

print (($n==1) ? "is" : "are") ;

Ruby

In Ruby, the operator is available and you can even embed it within a double quoted string ... (that's Ruby for you!)

method = miles < 3 ? "walk" : "ride"
or
print "That is a #{miles > 10 ? "LONG" : "short"} distance\n"

See Complete example source

Tcl, Tcl/Tk and Expect

Tcl is a command based language rather than an operator based one, so as you would expect the : and ? operator is not available everywhere - but you CAN use it within the expr command, or implicit expr deferred blocks - the conditions for if and while commands.

Here we are, checking under British licensing laws, whether we can sell you alcohol:

set mayyou [expr (($here > 17)?"may":"may not")]
puts "You $mayyou buy a drink"


The full source code is here. As even with Tcl, I could place the square bracketed expression for evaluation into my puts, but I've decided to keep it clear rather than concise.

Want to know more?

We provide training courses on all the languages I have mentioned - we offer scheduled public courses if you have just one or two delegates, and we can run private courses (and even do so at your own offices) if you have a larger group.