Control Flow
if, elsif, and else work the way they do in most C-family languages — a parenthesized condition, then a block. Unlike C, the braces are mandatory even for a single statement.
use strict;
use warnings;
my $score = 73;
if ($score >= 90) {
print "A\n";
} elsif ($score >= 70) {
print "B\n";
} else {
print "C or below\n";
}
B
Perl also has unless, which is simply if with the condition negated — idiomatic for "do this unless some condition holds", often reading more naturally than if (!...). Similarly, until is while with the condition negated.
use strict;
use warnings;
my $age = 15;
print "Minor\n" unless $age >= 18;
my $n = 0;
while ($n < 3) {
print "while: $n\n";
$n++;
}
my $m = 0;
until ($m >= 3) {
print "until: $m\n";
$m++;
}
Minor while: 0 while: 1 while: 2 until: 0 until: 1 until: 2
Both if and unless, and both while and until, also have a postfix form — print "Minor\n" unless $age >= 18; above is exactly that, a whole statement followed by its condition, with no braces at all. Next: loops and foreach — the C-style for loop, foreach over a list, and last/next.
Practice exercise
Given my $temp = 85, print "hot" if $temp is above 80, "warm" if above 60, otherwise "cold".