if, elsif and unless
Conditionals choose which code runs. Perl's if looks like C's, with two differences: the braces are mandatory, and the "else if" keyword is spelled elsif (no second e).
if / elsif / else
use strict;
use warnings;
for my $hour (6, 13, 19, 23) {
my $greeting;
if ($hour < 12) {
$greeting = "Good morning";
} elsif ($hour < 18) {
$greeting = "Good afternoon";
} elsif ($hour < 22) {
$greeting = "Good evening";
} else {
$greeting = "Good night";
}
print "$hour:00 -> $greeting\n";
}6:00 -> Good morning
13:00 -> Good afternoon
19:00 -> Good evening
23:00 -> Good night
The conditions are tested from top to bottom, and only the first true branch runs. Remember that a condition is just a value in scalar context, judged by Perl's truth rules (0, "", "0" and undef are false).
Note: Writing
else ifis a syntax error in Perl. Useelsif.
unless
unless is the opposite of if: the block runs when the condition is false. It reads naturally for negative checks:
use strict;
use warnings;
my %user = (name => "lena", verified => 0, banned => 0);
unless ($user{verified}) {
print "Please verify your email, $user{name}.\n";
}
unless ($user{banned}) {
print "Welcome back!\n";
} else {
print "Access denied.\n";
}Please verify your email, lena.
Welcome back!
Tip:
unless ... elseis legal but hard to read. If you need anelse, rewrite it as anifwith the condition flipped. And never useunlesswith a complex condition likeunless ($a && !$b); double negatives confuse everyone.
Statement modifiers
For a single statement, put the condition after it. This postfix form exists for if and unless (and for loops, as you will see):
use strict;
use warnings;
my @cart = ("book", "lamp");
my $coupon = "";
print "Cart has ", scalar(@cart), " items\n" if @cart;
print "No coupon applied\n" unless $coupon;
print "Free shipping!\n" if @cart >= 3;Cart has 2 items
No coupon applied
Combining conditions
use strict;
use warnings;
sub ticket_price {
my ($age, $is_student) = @_;
return 0 if $age < 5;
return 6 if $age < 18 || $is_student;
return 8 if $age >= 65;
return 12;
}
for my $person ([3, 0], [15, 0], [22, 1], [40, 0], [70, 0]) {
my ($age, $student) = @$person;
print "Age $age", ($student ? " (student)" : ""), ": \quot;, ticket_price($age, $student), "\n";
}Age 3: $0
Age 15: $6
Age 22 (student): $6
Age 40: $12
Age 70: $8
Early return ... if ... lines like these, called guard clauses, keep code flat instead of deeply nested. (The [3, 0] pairs are array references; you will learn about them soon.)
Using and / or for control flow
Because && and || short-circuit, they can replace small if statements. The low-precedence and / or are preferred for this:
use strict;
use warnings;
my $debug = 1;
my $config_loaded = 0;
$debug and print "Debug mode is on\n";
$config_loaded or print "Using default settings\n";Debug mode is on
Using default settings
You will most often see this in the form open(...) or die "Cannot open: $!";.
No switch statement
Perl's old given/when "switch" feature was experimental for many years and is turned off by the use v5.42 feature bundle, so avoid it in new code. Use an if/elsif chain, or a hash that maps values to results:
use strict;
use warnings;
my %http_status = (200 => "OK", 301 => "Moved Permanently", 404 => "Not Found", 500 => "Server Error");
for my $code (200, 404, 418) {
my $text = $http_status{$code} // "Unknown status";
print "$code $text\n";
}200 OK
404 Not Found
418 Unknown status
Test yourself
How is "else if" spelled in Perl?
else ifelseifelsifelif
When does the block of unless ($ready) { ... } run?
- When
$readyis true - When
$readyis false - Always
- Never
Which is a valid single-line conditional?
print "ok" if $x > 1;if $x > 1 print "ok";if ($x > 1) print "ok";print "ok" elsif $x;