The given and when Statements
To test a single value for a bunch of different alternatives, recent
versions of Perl have what other languages sometimes call switch and case. Because we like to make Perl work like a
natural language, however, we call these given and when. (Since you’re already putting use v5.14 at the top, you should have this
functionality, which was introduced in 5.10.)
#!/usr/bin/perl
use v5.14;
print "What is your favorite color? ";
chomp(my $answer = <STDIN>);
given ($answer) {
when ("purple") { say "Me too." }
when ("green") { say "Go!" }
when ("yellow") { say "Slow!" }
when ("red") { say "Stop!" }
when ("blue") { say "You may proceed." }
when (/\w+, no \w+/) { die "AAAUUUGHHHHH!" }
when (42) { say "Wrong answer." }
when (['gray','orange','brown','black','white']) {
say "I think $answer is pretty okay too.";
}
default {
say "Are you sure $answer is a real color?";
}
}First the given part takes the
value of its expression and makes it the topic of conversation, so the
when statements know which value to
test. The cases are then evaluated by matching the argument of each
when against the topic to find the
first when statement that thinks the
topic’s value matches. The when
statements try to match in order, and as soon as one matches, it doesn’t
try any of the subsequent statements, but drops out of the whole
given construct.
The form of each when argument
("red" vs 42 vs /\w+, no
\w+/) determines the type of match performed, so strings match as strings, numbers ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access