Foundations
Conditionals
An if statement lets a Perl program choose a branch.
if statement
An `if` statement runs its block only when the condition is true.
Conditionals
conditionals.pl
Replay: real traced execution (multi-file project)
use strict;
use warnings;
my $temperature = 72;
my $status = "";
if ($temperature >= 80) {
$status = "warm";
} else {
$status = "comfortable";
}
print "temperature=$temperature\n";
print "status=$status\n";
use strict;
use warnings;
my $temperature = 55;
my $status = "";
if ($temperature >= 80) {
$status = "warm";
} else {
$status = "comfortable";
}
print "temperature=$temperature\n";
print "status=$status\n";
use strict;
use warnings;
my $temperature = 90;
my $status = "";
if ($temperature >= 80) {
$status = "warm";
} else {
$status = "comfortable";
}
print "temperature=$temperature\n";
print "status=$status\n";
$temperature ← 72, $status ← (empty)
4my $temperature→ 72 = 72; #@temperature=55, 905my $status→ (empty) = "";$status ← comfortable
8 $status = "warm";9} else {10 $status→ comfortable = "comfortable";11}print "temperature=$temperature ";
13print "temperature=$temperature72\n";14print "status=$statuscomfortable\n";outputtemperature=72 status=comfortable
$temperature ← 55, $status ← (empty)
4my $temperature→ 55 = 55;5my $status→ (empty) = "";$status ← comfortable
8 $status = "warm";9} else {10 $status→ comfortable = "comfortable";11}print "temperature=$temperature ";
13print "temperature=$temperature55\n";14print "status=$statuscomfortable\n";outputtemperature=55 status=comfortable
$temperature ← 90, $status ← (empty)
4my $temperature→ 90 = 90;5my $status→ (empty) = "";$status ← warm
7if ($temperature90 >= 80) {8 $status→ warm = "warm";9} else {print "temperature=$temperature ";
13print "temperature=$temperature90\n";14print "status=$statuswarm\n";outputtemperature=90 status=warm
What Happens
$temperaturestarts at72.- Perl checks whether
$temperature >= 80. 72 >= 80is false.- The
elsebranch sets$statustocomfortable. - The program prints
temperature=72andstatus=comfortable.
Branch Picture
| temperature | comparison | status | | --- | --- | --- | | 55 | false | comfortable | | 72 | false | comfortable | | 90 | true | warm |
Try It
Exercise: conditionals.pl
Reproduce status=comfortable for temperature 72, then use the pinned temperatures 55 and 90 to identify each branch.