ela

Tutorial, lesson 4 of 9

Choosing a value

FizzBuzz counts from 1 to 15, and says Fizz for a multiple of 3, Buzz for a multiple of 5 and FizzBuzz for both. fizzbuzz chooses with a switch that gives a value: return switch, and each case holds one value after its ;. The remainder of 15 decides, and case 3, 6, 9, 12 matches any of the four.

The else is required: a switch that gives a value must give one whatever comes in. Take its line out and run the script: it stops before line 1, saying so.

A case holds one value, not lines of work. Work of several lines goes in a proc, and the case calls it: case 0; describe($n).

For a choice of two, a one-line if gives a value: if cond; a else b, the else required again, and else if chains a third; in brackets, as kind is, it may run over lines. An if over several lines gives none; a choice among many is the switch.

fizzbuzz could be the chain instead: try return if $n % 15 == 0; "FizzBuzz" else if $n % 3 == 0; "Fizz" else if $n % 5 == 0; "Buzz" else "$n".

What it prints
1
2
Fizz
4
Buzz
Fizz
7
8
Fizz
Buzz
11
Fizz
13
14
FizzBuzz
9: a multiple of 3
10: a multiple of 5
11: neither