Skip to content
Tutorials Center
My learning

Topics

Lesson 14 of 43 ยท Control Flow

Conditionals

Learn how Perl makes decisions with if, elsif, else, unless, the ternary operator and statement modifiers, and which values Perl treats as true or false.

A program that always does the same thing is not very useful. Conditionals let your code choose: print a warning only if a file is missing, give a discount only to members, stop only when a value looks wrong. Perl gives you several ways to write a decision, and picking the right one makes code read almost like English.

Before the syntax, you need to know one Perl rule: Perl has no separate boolean type. Instead, every value is either true or false when you ask. This lesson covers those truth rules first, because they decide how every if behaves.

Perl is not installed on this site, so the Perl code below is read-only. Its output was produced by a real Perl 5.42 run. The interactive examples are Python stand-ins that copy Perl's rules, so you can see the logic in action.

What is true and what is false

Perl treats exactly these values as false:

  • the number 0 (and 0.0)
  • the empty string ''
  • the string '0'
  • undef
  • an empty list, which means an empty array or hash in a test

Everything else is true. That includes the strings '0.0', '00' and ' ' (a single space), and the string 'a'.

Only five things are false

0 The number zero.
Empty string Two quotes with nothing between.
'0' The string with just a zero.
undef No value at all.

An empty array or hash is false, too.

1 / 2

You can check this with a loop. This read-only program prints the verdict for several values:

PERL
use v5.36;

for my $v (0, 1, '', '0', '0.0', '00', ' ', 'a', undef) {
    my $label = defined $v ? "'$v'" : 'undef';
    say "$label is ", ($v ? 'true' : 'false');
}
TEXT
'0' is false
'1' is true
'' is false
'0' is false
'0.0' is true
'00' is true
' ' is true
'a' is true
undef is false

The first value printed as '0' because Perl stores the number 0 and shows it as the digit. The string '0.0' is true because Perl only looks at the string '0', not at what the text means as a number.

The Python stand-in below applies Perl's rules with a small function. Python has its own truth rules (for example '0' is true in Python), so the function checks the Perl cases explicitly.

Python Stand-in: Perl's truth table

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Notice that [0], a list holding one zero, is true. Perl asks whether the list has elements, not what the elements are.

if, elsif and else

The basic form is if followed by a condition in parentheses and a block in curly braces. The braces are required, even for one statement.

PERL
use v5.36;

my $age = 20;

if ($age < 13) {
    say "child";
} elsif ($age < 20) {
    say "teen";
} else {
    say "adult";
}
TEXT
adult

Notice the spelling: elsif, with no e in the middle. Writing elseif or else if is a syntax error. Perl checks the conditions from the top and runs only the first block whose condition is true. If none matches, the else block runs when there is one.

Comparison needs the right operator for the kind of data. Use ==, <, > for numbers and eq, lt, gt for strings. Mixing them up is a classic bug, covered in Operators and Numbers.

unless

unless runs a block when the condition is false. It is if (!...) written as a word.

PERL
my $age = 20;

unless ($age < 18) {
    say "can vote";
}
TEXT
can vote

Use unless for simple, positive-sounding checks. Avoid unless with else or elsif, because reading "unless this, then that, else the other" makes people think twice. When a condition is complicated, write if with ! or not instead.

Statement modifiers

When the body is one simple statement, you can put the condition after it. This is the postfix form, also called a statement modifier:

PERL
my $age = 20;
my $debug = 0;

say "ok" if $age == 20;
say "fine" unless $age == 21;
say "debugging" if $debug;
TEXT
ok
fine

There are no parentheses and no braces. Modifiers read nicely for guards and early exits. For example, next unless defined $line; inside a loop. The limits are that the body must be one statement, and you cannot attach an elsif or else.

The ternary operator

The conditional operator ?: picks one of two expressions. It is the only operator with three parts, which is why it is called ternary.

PERL
my $age = 20;
my $label = $age >= 18 ? "adult" : "minor";
say $label;

my $x = 15;
my $size = $x < 10 ? "small"
         : $x < 20 ? "medium"
         :           "large";
say $size;
TEXT
adult
medium

Chaining ternaries is fine when you line the parts up as shown. If you need more than two or three branches, switch to elsif, which is clearer.

Combining conditions: &&, ||, // and the word forms

You combine tests with && (and), || (or) and ! (not). The word forms and, or and not do the same work with lower precedence, which makes them good for control flow:

PERL
my $x = 15;
say "in range" if $x > 1 and $x < 100;

open(my $fh, '<', '/no/such/file') or say "cannot open";
TEXT
in range
cannot open

and and or short-circuit: the right side runs only when needed. That is why open(...) or ... works, since the fallback runs only when open fails. The full story of operators is in Operators and Numbers.

A subtle point is that || treats 0 and '' as false. When those are valid values, use defined-or, //, which checks only for undef:

PERL
my $zero = 0;
my $d1 = $zero || 10;   # 10, because 0 is false
my $d2 = $zero // 10;   # 0, because 0 is defined
say "$d1 $d2";

my $name;
say $name // "guest";
TEXT
10 0
guest

Use // for defaults whenever zero or an empty string would be a legitimate input, such as a quantity or a search term.

Here is a stand-in that shows the same difference using Python's or and an explicit is None test:

Python Stand-in: || versus //

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Arrays and hashes as conditions

An array in a condition is true when it has at least one element, and a hash is true when it has at least one key. That makes common checks short:

PERL
my @queue = ();
my %settings = ();

say "queue is empty"    unless @queue;
say "no settings given" unless %settings;
TEXT
queue is empty
no settings given

This works because a condition gives the array scalar context, where it becomes its element count. See Context: Scalar vs List for why.

Nested conditions and early exits

Deep nesting is hard to read. A common Perl habit is to handle the odd cases first and leave the main path unindented:

PERL
sub describe_age ($age) {
    return "missing" unless defined $age;
    return "invalid" if $age < 0;
    return "child"   if $age < 13;
    return "adult";
}

Each line either answers and leaves the subroutine or lets the next line try. You will write subroutines like this in Subroutines.

A note about given and when

Older Perl books show a given/when construct as Perl's switch, often with the smartmatch operator ~~. It has always been marked experimental, its behavior is subtle, and Perl's developers planned to remove it in version 5.42 before deciding to keep it. Treat it as something to avoid in new code. For multi-way choices use an if/elsif chain, or a hash that maps values to actions (a dispatch table, covered in Scope, Closures and Recursion).

Multi-way choices: given/when and alternatives

Some languages have a switch. Perl's version is given/when, enabled with use feature 'switch':

PERL
use v5.10;
use feature 'switch';
no warnings;
for my $score (95, 72, 40) {
    given ($score) {
        when ($_ >= 90) { say "A" }
        when ($_ >= 70) { say "C" }
        default         { say "F" }
    }
}

It prints A, C, F. Each when block ends the given automatically (there is no fall-through), and default catches everything else. The catch: given/when has been marked experimental for years, relies on the quirky smartmatch operator ~~, and has been slated for removal. Do not use it in new code. Two portable alternatives:

PERL
# 1. A one-pass topicalizer with if and last
for my $v (qw(7 apple x)) {
    for ($v) {
        if (/^\d+$/)       { say "$v is a number"; last }
        if ($_ eq 'apple') { say "$v is a fruit";  last }
        say "$v is something else";
    }
}

# 2. A dispatch hash of code references
my %action = (start => sub { "go" }, stop => sub { "halt" });
for my $cmd (qw(start stop jump)) {
    say "$cmd: ", ($action{$cmd} // sub { "unknown" })->();
}

The inner for ($v) aliases $_ to the value, so each test reads like a case, and last leaves the block. The hash is the better choice when the cases are plain strings.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which of these values is TRUE in Perl?

    Only 0, the empty string, '0', undef and empty lists are false. The string '0.0' is true because it is not exactly '0'.
  2. 2. How do you spell the middle branch of an if chain in Perl?

    Perl uses elsif. Both else if and elseif are syntax errors.
  3. 3. What does say "hi" if $ready; do?

    A statement modifier runs the statement only when the condition is true. No parentheses or braces are needed.
  4. 4. You want a default of 10 but 0 must be kept as a valid value. Which operator is right?

    The defined-or operator // replaces only undef, while || also replaces 0 and the empty string.
  5. 5. What does say 'empty' unless @items; print when @items has no elements?

    An empty array is false in a condition, so unless runs the statement and prints empty.

Summary

  • Perl has no boolean type: 0, '', '0', undef and empty lists are false, and everything else is true.
  • Use if, elsif (one word, no extra e) and else; braces are always required.
  • unless runs when a condition is false, and statement modifiers put a simple if or unless after one statement.
  • The ternary ?: picks between two expressions, and // supplies a default only for undef.
  • Arrays and hashes are true when they are not empty; avoid given/when in new code.

Next, repeat actions with Loops and Loop Control.