Raku Logic
raku(1) offers several logical flow constructs.
If
if structures can be written in two ways.
if $a < 2 {
say 'Hello, world!'
}
say 'Hello, world!' if $a < 2 ;No matter the way it is written, the condition always evaluates first.
Fall-through conditions are specified with elsif and else clauses.
if $b = 0 {
say 'zero'
} elsif $b < 0 {
say 'negative'
} else {
say 'positive'
}As with any other boolean contexts, a condition can be inverted with either the ! or not operators.
Unless
The unless structure is simply a negated if structure. It cannot take an else or elsif clause.
unless 2 <= $a {
say 'Hello, world!'
}
With
The with structure is like an if structure that branches based on whether a variable is declared.
my $b;
with $b {
say 'This never happens'
}
$b = 1;
with $b {
say '$b is set'
}
Without
A negated with structure.
my $b;
without $b {
say '$b is unset'
}
$b = 1;
without $b {
say 'This never happens'
}
For
To loop over the elements of an array, try:
my @a = 1,2,3;
for @a -> $b {
say $b
}
Loop
A classic loop.
loop (my $i = 0; $i < 5; $i++) {
say $i
}
Given
To check a value for one or more conditions and branch based on those results, try:
my $a = 0;
given $var {
when 1..10 { say '$a is within [1,10]' }
when Int { say '$a is an integer' }
when 42 { say '$a is exactly 0' }
default { say "the fall-through case" }
}After matching a condition, the given structure is exited immediately. To override this behavior and continue trying cases, use the proceed keyword.
given $var {
when 1..10 { say '$a is within [1,10]'; proceed }
when Int { say '$a is an integer'; proceed }
when 42 { say '$a is exactly 0' }
default { say "the fall-through case" }
}But be sure to not include proceed on the penultimate case unless the fall-through case is intended to always execute.
