How to use the Perl ternary operator

In most languages there is an operator named the "ternary" operator that lets you write concise if/then statements. This makes for less verbose, which is generally a good thing. Perl also has a ternary operator, and I'll demonstrate it here.

General syntax of the ternary operator

The general syntax for Perl's ternary operator looks like this:

test-expression ? if-true-expression : if-false-expression

Let's take a look at a brief example to demonstrate this.

A brief example

Here's a brief example that demonstrates the Perl ternary operator. As you might guess, the first set of print statements will print true, and the second set prints false.

$TRUE = 1;
$FALSE = 0;

print "This should print 'true': ";
$TRUE ? print "true\n" : print "false\n";

print "This should print 'false': ";
$FALSE ? print "true\n" : print "false\n";

(I use $TRUE and $FALSE variables because I think they're easier to remember than 1 and 0, especially if you're new to Perl.)

A more complex example

Here's a slightly more complicated example to demonstrate the use of a comparison/equality operator in the "test expression" portion of the ternary operator:

# set the speed
$speed = 90;

# somewhere later in the program ...
$speed > 55 ? print "I can't drive 55!\n" : print "I'm a careful driver\n";

As you might guess, this segment of code will print:

I can't drive 55!

(Which summarizes my driving habits.)

The ternary operator is cool -- I hope you like it!