Switch Statements: given, when, default

Learn about switch statements in Perl.

We'll cover the following

The given statement

Perl 5.10 introduced a new construct named given as a Perlish switch statement. It didn’t quite work out; given is still experimental, although less buggy in newer releases. We should avoid it unless we know exactly what we’re doing.

The when statement

If we need a switch statement, we can use for to alias the topic variable $_ and use when to match it against simple expressions with smart matchThe smart match operator, ~~, compares two operands and returns a true value if they match. semantics. Here’s how to write the Rock, Paper, Scissors game:

Note: Perl executes the default rule when none of the other conditions match.

Get hands-on with 1200+ tech skills courses.