Perl unless Statement

The unless statement will execute the block when a condition expression is evaluated as false – it is the reverse of the if statement, i.e. like an statement with the opposite condition.

The unless statement is an alternative to the conditional if statement. Regardless the if statement which executes a block of code if a condition is true, the Perl unless statement executes a block of code if the condition is false.

You can regard the unless statement like the negative or opposite of if. Sometimes it is useful to use unless instead of if, especially when you want to optimize your code or to make it more legible.

You can use the unless statement either in connection with the else and elsif clauses if your conditional statement has more than one branch, or as a modifier.

You have two syntax forms for the unless conditional statement: a general form and a short form where unless is used as a modifier.

The general syntax form is as follows:

unless (EXPR) BLOCK elsif (EXPR) BLOCK ... else BLOCK
where:
 
  • EXPR is a Boolean conditional expression
  • the elsif and else clauses are optional and are used if you want to check a certain sequence of conditional expressions and find out which one of them is true
  • BLOCK consists of one or more statements enclosed in curly braces; in the construction of a block, the curly braces are always required.

You can split the general conditional Perl unless statement as follows:

a simple unless statement

unless (EXPR) BLOCK
If the EXPR condition will be evaluated false, Perl interpreter will execute the BLOCK, otherwise it will skip to the statement or declaration after the block. In this format you use neither the else nor the elsif clauses.

unless-else format

unless (EXPR) BLOCK else BLOCK
Perl will evaluate the conditional EXPR and if the result is false, it will continue with the execution of the BLOCK after the conditional expression, otherwise the script will continue with the block that follows the else clause.

unless-elsif-else format

unless (EXPR) BLOCK elsif (EXPR) BLOCK ... else BLOCK
This is the general format. If you have more than one branch in a conditional statement, you can use the unless statement in connection with elsif clause that allows you to check as many conditional expressions as you need. You can finish the compound conditional statement using the else clause at the end of the form.

the syntax form where unless is used as an expression modifier

You can use unless as a modifier, too. An expression modifier means a normal expression followed by a modifier that controls the execution of that expression.

The appropriate syntax form is as follows:

EXPR_MODIFIER unless (EXPR)
Perl will execute the above construction from right to left: the EXPR condition will be evaluated first and if the condition is false, Perl will continue the execution of the code with the EXPR_MODIFIER that precedes the Perl unless statement.

If the EXPR condition is true, the Perl interpreter will skip to the following line of code. You can use this form when your conditional statement has no more than one branch.

One of the simplest syntax form of the Perl unless statement is as follows:

unless (EXPR) BLOCK
If the EXPR condition is evaluated false, Perl interpreter will execute the block, otherwise it will skip to the statement or declaration after the block. In this format the else and elsif clauses are not used.  
 
See the following code snippet: 
#!/usr/local/bin/perl
 
use strict;
use warnings;
 
my $b = 0;
unless($b != 0) {
  $b += 1; 
}
print "b = $b\n";  # it outputs b = 1
Perl will evaluate the expression ($b != 0) and because it is false, it will execute the code between the curly braces of the block, i.e. it will increment the scalar variable $b by 1. The last line will print the value of $b.

The syntax form of the Perl unless statement with the else clause is as follows:

unless (EXPR) BLOCK else BLOCK
Perl will evaluate the conditional EXPR and if the result is false, it will continue with the execution of the block after the conditional expression, otherwise the script will continue with the block that follows the else clause.

Here is an example that finds the minimum of two numbers:

#!/usr/local/bin/perl
 
use strict;
use warnings;
 
my ($a, $b) = (35, 22);
 
unless($a > $b) {
  print "min($a, $b) = $a\n";
}
else {
  print "min($a, $b) = $b\n";
}
 
# it prints: min(35, 22) = 22
You can rewrite the Perl unless block using the ternary operator as in the following example:     
#!/usr/local/bin/perl
 
use strict;
use warnings;
 
my ($a, $b) = (35, 22);
 
print "min($a, $b) = ", $a < $b ? $a : $b, "\n";
 
# it prints: min(35, 22) = 22

If you have more than one branch in a conditional statement, you can use the Perl unless statement in connection with the elsif clause that allows you to check as many conditional expressions as you need.

You can finish the compound conditional statement using the else clause at the end of the form. Please note that the else clause can be omitted if it’s not necessary.

See the general syntax form:

unless (EXPR) BLOCK elsif (EXPR) BLOCK ... else BLOCK
See an example about how to implement it: 
#!/usr/local/bin/perl
 
use strict;
use warnings;
 
my $a = 12;
unless($a >= 0) {
  print "a is negative\n";
}
elsif ($a == 0) {
  print "a is equal to 0\n"; 
}
else {
  print "a is positive\n"; 
}
# it prints: a is positive
In this example, I used only one Perl elsif clause, but generally there can be more.

An expression modifier means a normal expression followed by a modifier that controls the execution of that expression.

The appropriate syntax form is as follows:

EXPR_MODIFIER unless (EXPR)
Perl will execute the above construction from right to left: the EXPR condition will be evaluated first and if the condition is false, Perl will continue the execution of the code with the EXPR_MODIFIER that precedes the Perl unless statement.
 
If the EXPR condition is true, the Perl interpreter will skip to the following line of code. You can use this form when your conditional statement has no more than one branch.

See the next example about how to use it:

#!/usr/local/bin/perl
 
use strict;
use warnings;
 
# define an array
my @colors = qw(blue green brown cyan white);
 
print "@colors\n" unless scalar(@colors) < 5;
# prints: blue green brown cyan white
If the @colors array has the number of elements greater than or equal to 5, this code will print the elements of the array separated by space, otherwise the script will continue with the next lines of code.
 
By enclosing @colors array between double quotes, we tell Perl interpreter to interpolate the @colors array and print its elements separated by space.

The exists function is useful to check if a key exists in a hash. See the following example where we use the Perl unless statement to check if a hash key exists:

#!/usr/local/bin/perl
 
use strict;
use warnings;
 
# initialize a hash
my %hash = ();
 
$hash{1} = 'one';
$hash{3} = 'three';
$hash{5} = 'five';
$hash{7} = 'seven';
 
foreach my $key (1..8) {
  print "Key not found: $key\n" unless exists $hash{$key};
}
The above hash has as keys the numbers 1, 3, 5 and 7. The foreach loop is used to iterate over the (1..8) set. The print function will display the hash keys that are not found in this set.

This code produces the following output:

Key not found: 2
Key not found: 4
Key not found: 6
Key not found: 8

See the following code snippet:

#!/usr/local/bin/perl
 
use strict;
use warnings;
 
while (my $line = <STDIN>) {
  chomp $line;
  last if lc ($line) =~ /quit/;
  next unless length $line > 0;
  print "Line: $line\n";
}
Here, we’re reading a line at a time into $line; inside the while loop, at each iteration step:
 
  • the chomp function will remove the trailing newline from $line
  • the last control will finish the loop if the $line contains the word quit (the lc function is used to make the conditional test case insensitive)
  • the next control will reiterate the loop if the line read from STDIN is empty
  • in the case the $line is not empty, the content of $line will be printed

You can use the Perl unless statement to check if a variable is defined or not. Anytime you declare a variable in Perl without initializing it, automatically it will take the "undef" value (which is different either of 0 or ""). So we use the defined function to check-up if a variable is defined (it was assigned some value to it) or has the "undef" value.

Applied to aggregate types (such as arrays and hashes), defined is depreciated and does not tell you anything useful about that aggregate, but you can apply it to the aggregate elements. 

The following snippet code shows you how to use unless and defined for scalar variables:

#!/usr/local/bin/perl
 
use strict;
use warnings;
 
my ($a, $b) = (1);
print "\$a is defined\n" unless !defined($a);
print "\$b is not defined\n" unless defined($b);
The following example is for the elements of an array: 
#!/usr/local/bin/perl
 
use strict;
use warnings;
 
# initializing an array
my @array = qw(zero one two three four);
 
$array[7] = "seven";
$array[9] = "nine";
 
for(my $i=0; $i<=20; $i++) {
  print "$i, " unless defined($array[$i]);
}
print "\n";
# it displays the indices of the undefined elements:
# 5, 6, 8, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20,