Conditional Statements
Learn how to control the flow of a Perl program using if, elsif, else, unless, and postfix conditionals.
Introduction
Almost no useful program runs the same code every single time. Programs need to make decisions: is this user logged in, is this number negative, did this file exist? Perl gives you several ways to branch your code based on a condition, and it is a bit more flexible than most languages because it also lets you write conditionals backwards, as a modifier at the end of a statement.
In this lesson you will learn the standard if/elsif/else structure, its negated cousin unless, the compact postfix form, and how Perl decides whether a value counts as true or false in the first place.
- How to write if, elsif, and else blocks.
- How unless inverts a condition for readability.
- How postfix conditionals let you write one-line decisions.
- What Perl considers "true" and "false".
The if Statement
The if statement evaluates an expression inside parentheses. If that expression is true, the block of code inside the curly braces runs. Unlike some languages, Perl always requires the curly braces, even for a single statement — this avoids a whole class of bugs where an extra line accidentally falls outside the block.
use strict;use warnings;
my $age = 20;
if ($age >= 18) { print "You are an adult.\n";}Click Run to see what this code prints.
elsif and else
When you need to check multiple conditions in sequence, chain elsif clauses after the initial if. Note the spelling: it is elsif, not "else if" and not "elseif" — a very common typo for newcomers. A final else block, with no condition of its own, catches everything that did not match any of the earlier branches.
use strict;use warnings;
my $score = 72;
if ($score >= 90) { print "Grade: A\n";} elsif ($score >= 80) { print "Grade: B\n";} elsif ($score >= 70) { print "Grade: C\n";} else { print "Grade: F\n";}Click Run to see what this code prints.
Perl evaluates each condition top to bottom and stops at the first one that is true, just like in most other languages. If none of the if/elsif conditions match, the else block runs as the fallback.
The unless Statement
unless is the mirror image of if — the block runs when the condition is false. It exists purely for readability. "unless the file exists, create it" often reads more naturally than "if the file does not exist, create it." Use it sparingly, though: unless combined with elsif or a complicated condition can quickly become confusing to read.
use strict;use warnings;
my $is_logged_in = 0;
unless ($is_logged_in) { print "Please log in first.\n";}Click Run to see what this code prints.
Perl does not support an "unelsif" keyword. If your unless needs an else branch, that is fine (unless (...) { } else { }), but avoid stacking multiple negated conditions — reach for if/elsif instead once it gets complex.
Postfix Conditionals
For simple, single-statement decisions, Perl lets you write the condition after the statement instead of wrapping everything in braces. This is called a statement modifier, and it is one of Perl's most distinctive, readable features.
use strict;use warnings;
my $temperature = 105;
print "Warning: high temperature!\n" if $temperature > 100;print "Temperature is normal.\n" unless $temperature > 100;Click Run to see what this code prints.
Postfix conditionals only work with a single statement — you cannot attach an elsif or else to them, and you cannot use them for multi-statement blocks. When your logic grows beyond one line, switch back to the block form.
Truthiness in Perl
Perl does not have a strict boolean type. Instead, every value is evaluated for truthiness when used in a condition. Understanding this list will save you from a lot of confusion later.
| Value | Considered |
|---|---|
| 0 | False |
| "0" (the string zero) | False |
| "" (empty string) | False |
| undef | False |
| () (empty list, in list context) | False |
| Any other number | True |
| Any other non-empty string (including "0.0" and "00") | True |
The string "0.0" is TRUE in Perl, even though it looks like zero, because only the exact string "0" is special-cased as false. This trips up a lot of beginners coming from other languages.
Nested Conditionals
You can nest if statements inside one another to check increasingly specific conditions. Keep nesting shallow where possible — deeply nested conditionals are hard to read, and often an elsif chain or a subroutine is a clearer way to express the same logic.
use strict;use warnings;
my $username = "admin";my $password = "secret123";my $correct_password = "secret123";
if ($username eq "admin") { if ($password eq $correct_password) { print "Access granted.\n"; } else { print "Incorrect password.\n"; }} else { print "Unknown user.\n";}Click Run to see what this code prints.
Notice eq is used above, not ==. Perl uses eq/ne/lt/gt/le/ge for string comparisons and ==/!=/</>/<=/>= for numeric comparisons. Mixing them up is one of the most common Perl beginner mistakes.
Common Mistakes
- Using == to compare strings instead of eq (this compares them numerically, which can silently give wrong results).
- Forgetting that curly braces are mandatory around if/unless blocks in Perl, even for one statement.
- Writing "elseif" or "else if" instead of the correct "elsif".
- Assuming the string "0.0" or "00" is false — only the exact string "0" and empty string "" are false.
- Chaining unless with elsif, which Perl does not support directly.
Best Practices
- Prefer if over unless once you need an elsif or complex logic — unless reads best only for simple, single-condition checks.
- Use postfix conditionals for short, guard-clause-style statements to keep code compact and readable.
- Always use eq/ne for strings and ==/!= for numbers to avoid subtle bugs.
- Keep nesting to two or three levels deep; refactor deeper logic into a subroutine.
- Add use strict; use warnings; to every script so Perl catches accidental typos in variable names inside conditions.
Frequently Asked Questions
Not a built-in classic one in older Perl versions. Modern Perl (5.10+) offers an experimental given/when construct, but it is discouraged; most Perl developers use if/elsif chains or hash-based dispatch tables instead.
Yes — unless (...) { ... } else { ... } is valid. What is not allowed is attaching an elsif to an unless.
They behave identically at runtime. Postfix if is purely a shorter syntax for a single statement and cannot have elsif or else attached.
Yes: condition ? value_if_true : value_if_false, exactly like in C, JavaScript, and many other languages.
Key Takeaways
- if, elsif, and else let you branch based on a condition; curly braces are always required.
- unless is a readability-focused inverse of if, best used for simple checks.
- Postfix conditionals (STATEMENT if CONDITION;) offer a compact one-line form.
- Only 0, "0", "", undef, and the empty list are false in Perl — everything else is true.
- Use eq/ne for strings and ==/!= for numbers.
Summary
Conditionals are the foundation of decision-making in any program, and Perl gives you several flavors: full if/elsif/else blocks, the readability-focused unless, and compact postfix modifiers. Next, you will learn how to repeat code with Perl's loop constructs.