2.4.2 The unless Statement
Perl also has an unless statement which is akin to the if statement. However, the conditional of the unless statement is evaluated as negated. For example, we can write a small program that prints if an input temperature is above the boiling point of water using an if statement.
Program 2.12
#!/usr/bin/perl
#file if10.pl
use strict;
print "Please enter a temperature in Fahrenheit>> ";
my $temperature = ;
chomp $temperature;
if ($temperature > 212){
print "$temperature F is above the boiling point of water\n";
}
The exact same program can be written using the unless statement. To do so, we have to logically invert the conditional of the if statement. The program is given below.
Program 2.13
#!/usr/bin/perl
#file unless1.pl
use strict;
print "Please enter a temperature in Fahrenheit>> ";
my $temperature = ;
chomp $temperature;
unless ($temperature <= 212){
print "$temperature F is above the boiling point of water\n";
}
A couple of interactions with this program are given below.
%unless1.pl
Please enter a temperature in Fahrenheit>> 300
300 F is above the boiling point of water
%unless1.pl
Please enter a temperature in Fahrenheit>> 20
The program does not do anything at all if the value entered by the user in response to the program’s prompt is not above 212 degrees F. It comes back empty-handed in such a situation.
The unless statement has a second version with an else. It works similarly to the if-else combination we have seen earlier. It does not have a third version with elsifs. A program that illustrates the second version is given below.
Program 2.14
#!/usr/bin/perl
#file unless2.pl
use strict;
print "Please enter a temperature in Fahrenheit>> ";
my $temperature = ;
chomp $temperature;
unless ($temperature <= 212){
print "$temperature F is above the boiling point of water\n";
}
else{
print "$temperature F is below the boiling point of water\n";
}
Two interactions with this program are given below.
% unless2.pl
Please enter a temperature in Fahrenheit>> 300
300 F is above the boiling point of water
%unless2.pl
Please enter a temperature in Fahrenheit>> 0
0 F is below the boiling point of water
