Setting the topic with given
In the example in the previous section, we used a chained if
—elsif
construction. Let's take a look at this once again:
if $step eq 'up' {$y--} elsif $step eq 'down' {$y++} elsif $step eq 'right' {$x++} elsif $step eq 'left' {$x--} elsif $step eq 'take-it' {take @matrix[$y][$x]}
It is clearly seen that all the branches contain the same code, which compares the current value of the $step
variable with one of the predefined values. While being simple and straightforward, this is not the most elegant way of doing such comparisons.
In some languages such as C and C++, the switch
and case
keywords help reorganize the if
-else
chain. In Perl 6, we use given
and when
. The preceding code can be rewritten in the following way:
given $step { when 'up' {$y--} when 'down' {$y++} when 'right' {$x++} when 'left' {$x--} when 'take-it' {take @matrix[$y][$x]} }
What happens here is that given
takes the $step
variable and makes it the...