Conditions and loops
if / elsif / unless, for over a list or range, while, statement modifiers, and next / last.
Runs in Zerethon IDE · Perl 5.40
Official Perl documentation ↗
main.pl
use v5.40;
for my $n (1 .. 5) {
if ($n % 2 == 0) {
say "$n even";
} elsif ($n == 5) {
say "$n last";
} else {
say "$n odd";
}
}
my $i = 3;
while ($i > 0) {
$i--;
next if $i == 1;
say "i = $i";
}
my @fruits = ("apple", "pear");
for my $index (0 .. $#fruits) {
say "$index $fruits[$index]";
}
my $temperature = -2;
say "freezing" unless $temperature > 0;
Output
1 odd 2 even 3 odd 4 even 5 last i = 2 i = 0 0 apple 1 pear freezing
- The braces are always required, even for one statement; or put the condition after it:
say "x" if $ok;. nextskips to the next round of a loop andlastleaves it (Perl'scontinueandbreak).- False values are
0,"0",""andundef; everything else is true. for my $item (@list)gives each element; inside a loop without a named variable the element is$_.