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

temperature
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";
  1. $temperature ← 72, $status ← (empty)

    4my $temperature→ 72 = 72; #@temperature=55, 905my $status→ (empty) = "";
  2. $status ← comfortable

    8    $status = "warm";9} else {10    $status→ comfortable = "comfortable";11}
  3. print "temperature=$temperature ";

    13print "temperature=$temperature72\n";14print "status=$statuscomfortable\n";
    outputtemperature=72
    status=comfortable
  1. $temperature ← 55, $status ← (empty)

    4my $temperature→ 55 = 55;5my $status→ (empty) = "";
  2. $status ← comfortable

    8    $status = "warm";9} else {10    $status→ comfortable = "comfortable";11}
  3. print "temperature=$temperature ";

    13print "temperature=$temperature55\n";14print "status=$statuscomfortable\n";
    outputtemperature=55
    status=comfortable
  1. $temperature ← 90, $status ← (empty)

    4my $temperature→ 90 = 90;5my $status→ (empty) = "";
  2. $status ← warm

    7if ($temperature90 >= 80) {8    $status→ warm = "warm";9} else {
  3. print "temperature=$temperature ";

    13print "temperature=$temperature90\n";14print "status=$statuswarm\n";
    outputtemperature=90
    status=warm

What Happens

  1. $temperature starts at 72.
  2. Perl checks whether $temperature >= 80.
  3. 72 >= 80 is false.
  4. The else branch sets $status to comfortable.
  5. The program prints temperature=72 and status=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.