Skip to content
If, Unless, While, Until
step 1/5

Reading — step 1 of 5

Learn

~2 min readControl Flow and Subroutines

Perl has the standard control structures and a few unique twists.

if / elsif / else:

my $age = 18;
if    ($age < 13) { print "child\n"; }
elsif ($age < 20) { print "teen\n"; }
else              { print "adult\n"; }

unlessif with negated condition:

unless ($file_exists) {
    die "missing file";
}
# same as: if (!$file_exists) { die ... }

Statement modifiers — append the condition for one-liners:

print "adult\n" if $age >= 18;
print "warning\n" unless $logged_in;
$count++ while $count < 100;
print "$_\n" for 1..5;

Very Perl-idiomatic. Reads naturally for short conditions.

Comparison operators — Perl distinguishes numeric from string:

NumericString
==eq
!=ne
<lt
>gt
<=>cmp

Using the wrong one is a classic Perl bug:

if ("10" == "9")  { ... }    # TRUE — numeric
if ("10" eq "9")  { ... }    # false — string
if ("10" lt "9")  { ... }    # TRUE — string sort: "1" < "9"

Boolean context — what's truthy in Perl:

  • 0, "0", "", undef — all FALSE
  • Everything else (including "0.0", "false") — TRUE

The stringification trips people up: "0" is false, but "0.0" is true.

while and until:

my $n = 1;
while ($n < 100) { $n *= 2; }

until ($done) { ... }   # loops while NOT $done

for (C-style) and foreach (list iteration) — they're aliases:

for (my $i = 0; $i < 10; $i++) { print $i; }
foreach my $item (@list) { print $item; }
for my $item (@list) { print $item; }    # same as foreach
for (@list) { print $_; }                  # implicit $_

Range operator ..:

for (1..10) { print "$_ "; }
for my $c ('a'..'z') { print $c; }

last, next, redo:

  • last — break out of loop (= break in C)
  • next — skip to next iteration (= continue)
  • redo — restart current iteration without re-evaluating condition

Loop labels for nested loops:

OUTER: for my $i (1..10) {
    for my $j (1..10) {
        last OUTER if $i * $j > 20;
    }
}

Discussion

Ask a question, share an insight, or help someone who’s stuck.

Sign in to post a comment or reply.

Loading…