Conditions and comparison
| if, elsif, else | |
| unless | |
| The ternary operator | |
| and, or, not | |
| What is true |
if, elsif, else
The condition sits in parentheses and the block in braces. Braces are always required, even for one line, which removes the dangling-else bugs that other languages allow.
my $load = 85;
if ($load >= 90) {
print "critical\n";
} elsif ($load >= 80) {
print "warning\n";
} else {
print "ok\n";
}
perl demo.pl
warning
Note the spelling: elsif, not elseif and not else if. Two words also work, but the single word keeps the chain visibly one statement.
unless
unless is if with the test reversed. It reads better when the normal path is the empty one, such as bailing out on a missing argument.
The statement modifier form puts the condition after the action, which suits short guards:
my $file = shift @ARGV;
die "usage: prog FILE\n" unless defined $file;
print "processing $file\n" if -f $file;
perl demo.pl /etc/hostname
processing /etc/hostname
Do not stack modifiers. One condition after the statement is readable; two are a puzzle, so rewrite them as a full if block.
The ternary operator
When both branches only produce a value, the ternary operator keeps it to one line. It takes three parts: test, value when true, value when false.
my $count = 1;
my $label = $count == 1 ? "item" : "items";
print "$count $label\n"; # 1 item
perl demo.pl
1 item
Chain ternaries only when every branch is a plain value and the list stays short. Otherwise use if and elsif, which the next maintainer will read faster.
and, or, not
Perl has two families of logical operators that differ only in precedence. The symbolic ones, &&, || and !, bind tightly and work well inside expressions. The word forms, and, or and not, bind so loosely that they sit below assignment.
my $count = 1;
my $ok = $count > 0 && $count < 10;
print "in range\n" if $ok;
open my $fh, "<", "/etc/hostname" or die "open failed: $!\n";
perl demo.pl
in range
That last line is the idiom you will see everywhere: with or, the die belongs to the whole open statement. Written with ||, the same code would bind to the file name and always succeed silently.
What is true
Perl has exactly five false values: the number 0, the string "0", the empty string, an empty list, and undef. Everything else is true, including the strings "00" and "0.0", and the string "false".
Test for emptiness with length or defined when a value may be text that begins with zero:
my $answer = "0";
print "false\n" unless $answer; # prints false
print "empty\n" unless length $answer; # does not print
perl demo.pl
false
Next: while, for, next and last
Article author: Arthur Isaev