Conditions and comparison

Contents
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

Related articles
Perl
Perl course: zero to hero in 50 lessons
What is Perl and where it runs
Install Perl and check the version
Your first Perl script
The debugger as a REPL
Scalars and sigils
Numbers
Strings
Interpolation and quoting
Arrays
push, pop, shift and splice
Hashes
keys, values, exists and delete
Scalar and list context
Conditions and comparison
while, for, next and last
foreach and the default variable
Subroutines
Arguments in @_
References
Nested data structures
Regular expressions: match and anchors
Captures and named groups
Substitution with s///
split and join
grep and map
Sort and the Schwartzian transform
Read and write files
File tests and metadata
Directories and paths
die, warn and eval
Modules and Exporter
CPAN and cpanm
Objects with bless
Modern objects with Moo
Testing with Test::More
strict, warnings and diagnostics
Options with Getopt::Long
Environment and %ENV
system, backticks and pipes
One-liners with -n and -p
CSV and TSV processing
JSON with JSON::PP
HTTP clients with HTTP::Tiny
Sockets and IO::Socket
Databases with DBI
Capstone: todo CLI
Capstone: log report
Performance and profiling
Modern Perl tour
Hero roadmap: the whole course on one page
Install Perl on Windows 11
Install Perl on Ubuntu
Install Perl on Rocky Linux
Install Perl on macOS
Install Perl on FreeBSD
Perl in Docker
Banner image

Search this site

Channel @aofeed Chat @aofeedchat

Contacts and cooperation:
I recommend our hosting beget.com
Write to info@aredel.com if you:
1. Want to write an article for our site or translate an article into your native language.
2. Want to place thematically relevant ads on the site.
3. Ads on my site pass maximum censorship. If you see an ad block unsuitable for school-age children, shocking or misleading - please contact us by e-mail
4. Found a mistake, inaccuracy, bug, etc. on the site. ... .......
5. Articles can be shared on social media by clicking a network icon: