if, elsif, and unless in Perl
Branching with if, Perl's one-word elsif, and unless for the if-not case.
use strict;
use warnings;
my $hour = 14;
if ($hour < 12) {
print "morning\n";
} elsif ($hour < 18) {
print "afternoon\n";
} else {
print "evening\n";
}
# unless reads as if-not; save it for simple guards
my $queue = 0;
unless ($queue) {
print "queue is empty\n";
}
How it works
- The chain tests
$houragainst noon and 18:00; the braces are never optional. elsifis a single keyword — Perl rejects bothelse ifandelseif.unlessruns its block when the condition is false; best kept for simple guards.
Keywords and builtins used here
elseelsififmyprintunlessuse
The run, in numbers
- Lines
- 17
- Characters to type
- 266
- Tokens
- 59
- Three-star pace
- 80 tpm
At the three-star pace of 80 tokens a minute, this run takes about 44 seconds.
Step 1 of 3 in Control flow, step 4 of 27 in Language basics.