typestar

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

  1. The chain tests $hour against noon and 18:00; the braces are never optional.
  2. elsif is a single keyword — Perl rejects both else if and elseif.
  3. unless runs its block when the condition is false; best kept for simple guards.

Keywords and builtins used here

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.

Type this snippet

Step 1 of 3 in Control flow, step 4 of 27 in Language basics.

← Previous Next →