- publishing free software manuals
Perl Language Reference Manual
by Larry Wall and others
Paperback (6"x9"), 724 pages
ISBN 9781906966027
RRP £29.95 ($39.95)

Sales of this book support The Perl Foundation! Get a printed copy>>>

4.11 Switch statements

Starting from Perl 5.10, you can say

use feature "switch";

which enables a switch feature that is closely based on the Perl 6 proposal.

The keywords given and when are analogous to switch and case in other languages, so the code above could be written as

given($_) {
    when (/^abc/) { $abc = 1; }
    when (/^def/) { $def = 1; }
    when (/^xyz/) { $xyz = 1; }
    default { $nothing = 1; }
}

This construct is very flexible and powerful. For example:

use feature ":5.10";
given($foo) {
    when (undef) {
        say '$foo is undefined';
    }
    when ("foo") {
        say '$foo is the string "foo"';
    }
    when ([1,3,5,7,9]) {
        say '$foo is an odd digit';
        continue; # Fall through
    }
    when ($_ < 100) {
        say '$foo is numerically less than 100';
    }
    when (\&complicated_check) {
        say 'a complicated check for $foo is true';
    }
    default {
        die q(I don't know what to do with $foo);
    }
}

given(EXPR) will assign the value of EXPR to $_ within the lexical scope of the block, so it's similar to

do { my $_ = EXPR; ... }

except that the block is automatically broken out of by a successful when or an explicit break.

Most of the power comes from implicit smart matching:

when($foo)

is exactly equivalent to

when($_ ~~ $foo)

Most of the time, when(EXPR) is treated as an implicit smart match of $_, i.e. $_ ~~ EXPR. (See 4.11.4 for more information on smart matching.) But when EXPR is one of the below exceptional cases, it is used directly as a boolean:

In those cases the value of EXPR is used directly as a boolean.

Furthermore:

These rules look complicated, but usually they will do what you want. For example you could write:

when (/^\d+$/ && $_ < 75) { ... }

Another useful shortcut is that, if you use a literal array or hash as the argument to given, it is turned into a reference. So given(@foo) is the same as given(\@foo), for example.

default behaves exactly like when(1 == 1), which is to say that it always matches.

ISBN 9781906966027Perl Language Reference ManualSee the print edition