Course of Raku / Advanced / Control flow

given and when

When a program needs to choose between several alternatives, a chain of if and elsif checks can become long and repetitive. In that situation, the given/when construct is often clearer. It is similar to the switch statement found in other languages.

The given block takes a value and makes it the topic — the special variable $_. Each when block is then compared against that topic, and the first one that matches runs:

my $n = 2;

given $n {
    when 1 { say 'one' }
    when 2 { say 'two' }
    when 3 { say 'three' }
}

This program prints:

two

Unlike a switch in some other languages, there is no fall-through: as soon as a when matches, its block runs and the given block is finished. The remaining when blocks are not tested.

The default block

A default block runs when none of the when blocks matched. It plays the same role as the else branch of an if statement:

my $n = 5;

given $n {
    when 1 { say 'one' }
    when 2 { say 'two' }
    default { say 'many' }
}

Because $n is neither 1 nor 2, the program prints:

many

Also in this section

Practice

Complete the quiz that covers the contents of this section.

Exercises

This section contains 3 exercises. Examine all the topics of this section before doing the coding practice.

  1. Life stage from age
  2. Even, odd, or zero
  3. Match by type

Course navigation

Quiz — LEAVE   |   Matching ranges, types, and conditions