In Control flow§
See primary documentation in context for if
To conditionally run a block of code, use an if
followed by a condition. The condition, an expression, will be evaluated immediately after the statement before the if
finishes. The block attached to the condition will only be evaluated if the condition means True
when coerced to Bool
. Unlike some languages the condition does not have to be parenthesized, instead the {
and }
around the block are mandatory:
if 1 { "1 is true".say } ; # says "1 is true"
if 1 "1 is true".say ; # syntax error, missing block
if 0 { "0 is true".say } ; # does not say anything, because 0 is false
if 42.say and 0 { 43.say }; # says "42" but does not say "43"
There is also a form of if
called a "statement modifier" form. In this case, the if
and the condition come after the code you want to run conditionally. Do note that the condition is still always evaluated first:
43.say if 42.say and 0; # says "42" but does not say "43" 43.say if 42.say and 1; # says "42" and then says "43" say "It is easier to read code when 'if's are kept on left of screen" if True; # says the above, because it is true { 43.say } if True; # says "43" as well
The statement modifier form is probably best used sparingly.
The if
statement itself will either Slip
us an empty list, if it does not run the block, or it will return the value which the block produces:
my $d = 0; say (1, (if 0 { $d += 42; 2; }), 3, $d); # says "(1 3 0)" my $c = 0; say (1, (if 1 { $c += 42; 2; }), 3, $c); # says "(1 2 3 42)" say (1, (if 1 { 2, 2 }), 3); # does not slip, says "(1 (2 2) 3)"
For the statement modifier it is the same, except you have the value of the statement instead of a block:
say (1, (42 if True) , 2); # says "(1 42 2)" say (1, (42 if False), 2); # says "(1 2)" say (1, 42 if False , 2); # says "(1 42)" because "if False, 2" is true
The if
does not change the topic ($_
) by default. In order to access the value which the conditional expression produced, you have to ask for it more strongly:
$_ = 1; if 42 { $_.say } ; # says "1" $_ = 1; if 42 -> $_ { $_.say } ; # says "42" $_ = 1; if 42 -> $a { $_.say; $a.say } ; # says "1" then says "42" $_ = 1; if 42 { $_.say; $^a.say } ; # says "1" then says "42"