Conditional statements
Conditional statements allow you change the flow of the code.
Conditional statements operate with Boolean values that you've learned in a previous chapter and include if/else/elsif
and unless
.
When the result of expression in the brackets is true than the block surrounded by curly brackets is evaluated:
if (1 == 1) { say 'True'; } if (1 == 0) { say 'False'; }
When you want to do something when the expression is false you can use else
:
if (0) { say 'True'; } else { say 'False'; }
When you want to check the expression again you can use elsif
:
my $x = 1; if ($x == 0) { say 'x is zero'; } elsif ($x < 0) { say 'x is less than zero'; } else { say 'x is more than zero'; }
There is also a short form for if
statement:
my $x = 5; say 'True' if $x > 0;
unless
is an opposite to if
where not the true value determines whether the block is evaluated but the false value.
my $x = 5; say 'True' unless $x == 0;
Which is the same as:
my $x = 5; say 'True' if !($x == 0);
As you already know in Perl the truth values is everything that is not zero, so comparizon to 0 usually is not needed:
my $x = 5; say 'True' unless $x;
Exercise
Fix this code so it prints 'Hello'
instead of 'Bye'
by using logical operator and without changing $x
value.
my $x = 0; if ($x) { say 'Hello'; } else { say 'Bye'; }