Today I fixed the majority of the issues with Rakudo's 'when' blocks. When blocks do smartmatching against the current topic. For example, this:
when 'foo' { ... }
could also be written approximately like this:
if $_ ~~ 'foo' { ... }
The biggest difference is that 'when' blocks automatically break out to the innermost scope that has $_ as one of its formal parameters (either explicit or implicit), so:
for @numbers {
when 1..5 { say 'low' }
when 6..10 { say 'high' }
}
Could also be written as:
for @numbers {
if $_ ~~ 1..5 { say 'low'; break }
if $_ ~~ 6..10 { say 'high'; break }
}
(Which currently doesn't work in Rakudo, as we don't have control exceptions on loops handled properly yet.)
this lets us use the 'given' block, which just sets the topic for the block, to implement an idiomatic switch statement in Perl 6:
given $foo {
when 'A' { say 'got A' }
when 'B' { say 'got B' }
when 'C' { say 'got C' }
when '1' { say 'got 1' }
when '2' { say 'got 2' }
when '3' { say 'got 3' }
when /foo/ { say 'matched a regex' }
when 1..100 { say 'matched a range' }
when 'etc' { say 'you know... like this.' }
default { say 'When all else fails...' }
}
There's a handler for CONTINUE exceptions around every 'when' block to continue on through the block, so if you want to fall through, you just say:
given $num {
when '3' { say 'got 3'; continue }
when 1..100 { say 'got from 1 to 100' }
}
