Skip to content
LumenaryAcademy
Foundations 55 min

Control flow and subroutines

Conditions, loops and statement modifiers, then subroutines from the classic @_ style to modern signatures.

Code tested · 3AI-draftedAwaiting review by a computer scientist
MotivationH

Saying what you mean

Every language has if and loops, and Perl's look much like C's or JavaScript's. What makes Perl different is how many shapes of the same idea it offers. You can write if (!$ok) or unless ($ok). You can put a condition before a block or after a single statement: die "No input\n" unless @lines;. You can loop with a block or with a modifier: print for @names;.

This is Larry Wall's linguistics showing. Natural languages let you put the important part of a sentence first; Perl lets you put the action first when the action is the point and the condition is a detail, and the condition first when the decision is the point. Used well, it makes code read like a clear sentence. Used badly, it makes code a puzzle. This lesson shows the forms, and the house rules that experienced Perl programmers follow so that the result stays readable.

The second half is about subroutines, Perl's functions. Perl's original way of passing arguments, through a special array called @_, is simple and flexible and is still the style of most existing Perl code, so you need to read it fluently. Since Perl 5.36, signatures give subroutines named parameters like most languages have. You will learn both.

Worked examplesH

Conditions and loops

perl
use strict;
use warnings;
use feature qw(say);

my %temperature = (Reykjavik => -3, Cairo => 24, Quito => 14, Delhi => 31);

for my $city (sort keys %temperature) {
    my $t = $temperature{$city};
    my $word;
    if    ($t < 0)  { $word = 'freezing' }
    elsif ($t < 15) { $word = 'cool' }
    elsif ($t < 28) { $word = 'warm' }
    else            { $word = 'hot' }
    say "$city is $word ($t C)";
}

my @readings = (12, -1, 15, 999, 18, 20);
my $total = 0;
for my $r (@readings) {
    next if $r < 0;            # skip bad readings
    last if $r == 999;         # 999 marks the end of the data
    $total += $r;
}
say "total before the end marker: $total";

my $raining = 0;
say "no umbrella needed" unless $raining;   # unless means "if not"

my $n = 1;
$n *= 2 while $n < 100;        # statement modifier loop
say "first power of two from 100: $n";

my @grid = ([1, 2, 3], [4, 5, 6], [7, 8, 9]);   # rows (lesson 4 explains [...])
ROW: for my $row (@grid) {
    for my $cell (@$row) {
        next ROW if $cell % 2 == 0;    # leave this row at its first even cell
        print "$cell ";
    }
}
print "\n";

my @prices = (10, 20, 30);
$_ *= 1.1 for @prices;         # the loop variable is an alias: this changes @prices
say "with tax: @prices";

It printed:

text
Cairo is warm (24 C)
Delhi is hot (31 C)
Quito is cool (14 C)
Reykjavik is freezing (-3 C)
total before the end marker: 27
no umbrella needed
first power of two from 100: 128
1 7 
with tax: 11 22 33

The pieces

  • if / elsif / else. Note the spelling elsif, and that the braces are always required, even around one statement. That rule removes a whole family of bugs where a second line was meant to be inside an if but was not.
  • unless (COND) means if (!COND). Use it for simple negative conditions; avoid unless ... else and unless with complex conditions, which are hard to read.
  • Statement modifiers. A single statement can be followed by if COND, unless COND, while COND, until COND or for LIST. In next if $r < 0; the action reads first, which suits guard clauses: "skip this one if it is bad".
  • foreach. for and foreach are the same keyword. for my $r (@readings) { ... } gives a fresh variable each pass. Without a variable, the loop uses $_.
  • C-style for. for (my $i = 0; $i < 10; $i++) { ... } exists, but Perl programmers rarely need it: for my $i (0 .. 9) or for my $i (0 .. $#array) is clearer.
  • while and until. while (COND) { ... } loops while the condition is true; until loops while it is false.
  • next, last, redo. next starts the next pass, last leaves the loop (like break elsewhere), and the rarely used redo restarts the current pass without re-testing the condition.
  • Labels. A word in capitals followed by a colon names a loop. next ROW and last ROW act on the named loop instead of the innermost one, which makes nested loops much easier to control.

Definition— Aliasing in foreach

The loop variable of foreach is not a copy: it is an alias, another name for the actual element. Assigning to it changes the array. That is why $_ *= 1.1 for @prices; updated every price. The same is true of $_ inside map and grep blocks, so a map that modifies $_ modifies the original list.

The output 11 22 33 hides a detail: 10 * 1.1 is really 11.000000000000002 in binary floating point. Perl prints numbers with 15 significant digits by default, which rounds that away. For money, store whole cents or use sprintf "%.2f" when printing.

and, or and not

Perl has two sets of logical operators: &&, || and ! bind tightly, while and, or and not bind more loosely than anything else, even assignment. The loose ones exist for control flow:

perl
open my $fh, '<', $path or die "Cannot open $path: $!";   # good: or binds loosely
my $name = $input || 'anonymous';                          # good: || binds tightly
my $bad  = $input or 'anonymous';                          # bug: means (my $bad = $input) or 'anonymous'

The house rule most teams follow: || and && inside expressions, or and and between whole statements, such as "do this or die".

Common misconceptionsH

Three loop traps

Perl's loops are simple, but three behaviours catch people who come from other languages.

Misconception

"do { ... } while (COND); is a loop, so next and last work inside it." They do not. A do block is a single expression with a modifier attached, not a real loop block, so last inside it either exits some outer loop or dies with Can't "last" outside a loop block. When you need a loop that runs at least once and may exit early, write while (1) { ...; last unless COND; } instead.

Misconception

"while (my ($key, $value) = each %h) is the best way to walk a hash." It works, and you will see it in older code, but each hash has a single hidden iterator. If anything inside the loop calls keys %h, or leaves the loop early and something else later calls each on the same hash, iteration silently restarts or resumes in the wrong place. for my $key (sort keys %h) { my $value = $h{$key}; ... } has no hidden state and gives a predictable order, which is why most style guides prefer it.

Misconception

"I can push to or splice an array while looping over it with foreach." Changing the length of an array during a foreach over that same array is explicitly unsupported: Perl's documentation says not to do it, and the results depend on the version. Build a new array instead (my @keep = grep { ... } @items;), or loop over the indices backwards when you must delete in place: for my $i (reverse 0 .. $#items) { splice @items, $i, 1 if ...; }.

A positive habit to set against these traps: when a loop body grows past a dozen lines, move it into a subroutine with a clear name. The loop then reads as one sentence, process_order($_) for @orders;, and the subroutine can be tested on its own.

DefinitionsH

Subroutines the classic way

Definition— Subroutine

A named block of code declared with sub NAME { ... } and called as NAME(ARGS). The arguments arrive in the special array @_, flattened into one list. The subroutine returns the value of its return statement or, without one, the value of the last expression it evaluated. It can return a single scalar, a list or nothing.

perl
use strict;
use warnings;
use feature qw(say);

# Arguments arrive in @_. Copy them into named variables first.
sub area {
    my ($width, $height) = @_;
    $height //= $width;               # a default: a square
    return $width * $height;
}

# Several values out: return a list.
sub min_max {
    my @sorted = sort { $a <=> $b } @_;
    return ($sorted[0], $sorted[-1]);
}

# Named arguments: pass pairs and read them as a hash.
sub greet {
    my (%args) = @_;
    my $name     = $args{name}     // 'friend';
    my $greeting = $args{greeting} // 'Hello';
    return "$greeting, $name!";
}

# A sub can ask which context it was called in.
sub tags {
    my @tags = qw(perl text regex);
    return wantarray ? @tags : scalar @tags;
}

say "area 3x4: ", area(3, 4), ", square of 5: ", area(5);
my ($lo, $hi) = min_max(17, 3, 42, 8);
say "min $lo, max $hi";
say greet(name => 'Thandiwe');
say greet(greeting => 'Hola', name => 'Mateo');
say greet();
my @list  = tags();
my $count = tags();
say "tags: @list (count $count)";

# @_ is aliased to the caller's variables: changing $_[0] changes them.
sub shout { $_[0] = uc $_[0] }
my $word = 'quiet';
shout($word);
say "after shout: $word";

It printed:

text
area 3x4: 12, square of 5: 25
min 3, max 42
Hello, Thandiwe!
Hola, Mateo!
Hello, friend!
tags: perl text regex (count 3)
after shout: QUIET

Reading the classic style

  • Unpack @_ on the first line. my ($width, $height) = @_; is a list assignment: the first argument goes to $width, the second to $height, and a missing one leaves its variable undef. For a single argument you will often see my $x = shift;, because shift with no array inside a subroutine takes from @_.
  • Defaults with //=. "If $height is undef, set it to $width." This keeps 0 as a legitimate value, which ||= would not.
  • Returning lists. return ($sorted[0], $sorted[-1]); hands back two values, and my ($lo, $hi) = min_max(...) catches them.
  • Named arguments. Because the argument list is flat, a list of pairs can be read as a hash. Calls like greet(name => 'Mateo') are self-documenting and let callers leave out anything with a default. Large Perl code bases use this style constantly.
  • Context. wantarray is true when the caller wants a list, false when it wants a scalar, and undef when the result is thrown away. Use it sparingly: a subroutine whose meaning changes with context surprises readers. Built-ins such as localtime do it; your own code mostly should not.
  • Aliasing. The elements of @_ are aliases for the caller's arguments, just like the foreach variable. Assigning to $_[0] changed $word in the caller. Copying @_ into my variables first, as every example above does, avoids accidental changes.

A failed lookup or search usually ends with a bare return;. In list context that returns an empty list, and in scalar context undef, so both if (my $x = find(...)) and my @found = find(...) behave sensibly. Writing return undef; instead would give a one-element list (undef) in list context, which is true; that is a classic source of bugs.

Misconception

"Perl passes arrays to subroutines." It passes a flat list. process(@a, @b) delivers every element of both arrays in one @_, and the subroutine cannot tell where @a ended. To pass two separate arrays, pass references to them, process(\@a, \@b), as lesson 4 explains.

Worked examplesH

Signatures and state variables

Unpacking @_ by hand is repetitive, and nothing checks that the caller passed the right number of arguments. Subroutine signatures fix both. They were added as an experimental feature in Perl 5.20 and became stable in Perl 5.36. On 5.36 or newer, use v5.36; turns them on along with strict, warnings and say. On older Perls, such as the 5.34 that checks this course, you enable the feature and silence its "experimental" warning, which is harmless on newer versions too:

perl
use strict;
use warnings;
use feature qw(say signatures state);
no warnings qw(experimental::signatures);   # not needed on Perl 5.36 and later

sub gcd ($x, $y) {
    return $y == 0 ? $x : gcd($y, $x % $y);
}

sub label ($text, $width = 10, $fill = '.') {
    return $text . ($fill x ($width - length $text));
}

sub total ($first, @rest) {       # a slurpy array takes the remaining arguments
    my $sum = $first;
    $sum += $_ for @rest;
    return $sum;
}

sub next_ticket {
    state $number = 100;          # initialised once, kept between calls
    return ++$number;
}

say "gcd(84, 36) = ", gcd(84, 36);
say label('Name'), '|';
say label('Total', 8, '_'), '|';
say "total: ", total(1, 2, 3, 4);
say "tickets: ", join(' ', map { next_ticket() } 1 .. 3);

my $ok = eval { gcd(1); 1 };      # the wrong number of arguments dies
say "calling gcd(1) failed: ", $@ =~ s/ at .*//sr;

It printed:

text
gcd(84, 36) = 12
Name......|
Total___|
total: 10
tickets: 101 102 103
calling gcd(1) failed: Too few arguments for subroutine 'main::gcd' (got 1; expected 2)

What signatures give you:

  • Named parameters: sub gcd ($x, $y) declares two lexical variables and fills them from the arguments.
  • Arity checking: calling gcd(1) dies with a clear message instead of quietly running with $y undef. The last two lines of the program catch that error with eval, which lesson 6 covers properly, and trim the "at FILE line N" part with a substitution, which lesson 5 explains.
  • Defaults: $width = 10 is used when the argument is missing. Perl 5.38 added //= and ||= defaults, which also replace an undef or false argument.
  • Slurpy parameters: a final @rest or %opts takes all remaining arguments.

gcd also shows recursion: a subroutine that calls itself, here Euclid's algorithm for the greatest common divisor. Perl handles deep recursion fine, though it warns when a call chain goes more than 100 levels deep, a hint that a loop might be better.

Definition— state variable

A variable declared with state (Perl 5.10, enabled by use feature 'state' or any use v5.10 or later) is initialised the first time the code runs and then keeps its value between calls, like a static local in C. It is the clean way to give a subroutine a private counter or cache.

my and local

You will meet a second keyword, local, in older code and in a few special places. my creates a new lexical variable, visible only in the enclosing block: this is what you want almost always. local temporarily changes the value of a global variable until the enclosing block ends, and every subroutine called meanwhile sees the temporary value. Its main legitimate use today is adjusting Perl's special variables for a short stretch of code, such as local $/; to read a whole file at once (lesson 6). If you find yourself writing local on your own variables, use my instead.

ExplanationH

House rules for readable Perl

Teams that write a lot of Perl tend to agree on a handful of rules. They are worth adopting now, before habits form:

  1. Always use braces and indent consistently. Perl requires braces on blocks anyway; let a formatter (Perl::Tidy, lesson 8) handle the layout.
  2. Statement modifiers for short guards only. return unless @items; and next if $line eq ''; are clear. A modifier hanging off a long, complicated statement hides the condition.
  3. No unless ... else, and no unless with && or || inside.
  4. Unpack arguments at the top of every subroutine, or use signatures where your Perl allows.
  5. Bare return; for failure, not return undef;.
  6. or die for errors from system calls, || and // for defaults.
  7. Avoid given/when and the smartmatch operator ~~. They were experimental for many years and their behaviour is notoriously hard to predict. Use if/elsif, or a hash that maps keys to subroutines (a dispatch table, shown in lesson 4).
  8. Do not use prototypes (sub max($$) with symbols in the parentheses, without a signature feature). They look like parameter lists but change how calls are parsed, and they are only useful for writing functions that behave like built-ins.
Exercises

Exercises

1. Control flow and subroutines

Warm-upComputational

What does this program print?

use strict;
use warnings;
use feature qw(say);
my @n = (5, 0, 7, -2, 9);
my @out;
for my $x (@n) {
    next unless $x;
    last if $x < 0;
    push @out, $x * 2;
}
say "@out";

2. Control flow and subroutines

CoreComputational

What does this program print?

use strict;
use warnings;
use feature qw(say);
my @w = qw(a b c);
for my $x (@w) { $x = uc $x }
my @v = map { $_ . $_ } @w;
say "@w @v";

3. Control flow and subroutines

CoreComputational

What does this program print?

use strict;
use warnings;
use feature qw(say);
sub ctx { return wantarray ? "list" : "scalar" }
my @a = ctx();
my $s = ctx();
say "$a[0] $s ", scalar(ctx());

4. Control flow and subroutines

CoreComputational

What number does this program print?

use strict;
use warnings;
use feature qw(say state);
sub counter {
    state $n = 0;
    return $n += 10;
}
counter() for 1 .. 3;
say counter();

5. Control flow and subroutines

CoreComputational

What does this program print?

use strict;
use warnings;
use feature qw(say);
my $input = '';
my $x = $input || 'guest';
my $y = $input // 'guest';
say "[$x] [$y]";

6. Control flow and subroutines

StretchComputational

What does this program print? (Ignore any trailing space.)

use strict;
use warnings;
use feature qw(say);
OUTER: for my $i (1 .. 3) {
    for my $j (1 .. 3) {
        next OUTER if $j > $i;
        print "$i$j ";
    }
}
print "\n";

7. Control flow and subroutines

CoreComputational

What does this program print? It prints three lines; type them separated by single spaces.

use strict;
use warnings;
use feature qw(say signatures);
no warnings qw(experimental::signatures);
sub pair ($left, $right = 'none') { return "$left/$right" }
say pair('a');
say pair('a', 'b');
my $r = eval { pair('a', 'b', 'c') } // 'died';
say $r;

8. Control flow and subroutines

StretchComputational

This program searches for an even number and finds none. What does it print, and why?

use strict;
use warnings;
use feature qw(say);
sub find_even {
    for my $n (@_) { return $n if $n % 2 == 0 }
    return undef;
}
my @found = find_even(1, 3, 5);
say scalar(@found), " ", (@found ? "true" : "false");
Choose one

Further reading and resources

  • perlsynThe official description of Perl's statements, loops, statement modifiers and loop control.
  • perlsubEverything about subroutines, including @_, signatures, context, prototypes and local.
  • featureThe list of optional features (say, state, signatures, try and more) and which version bundles enable them.
  • perlopOperator precedence, which explains the difference between || and or.