Perl UNLESS... ELSE statement

Perl UNLESS... ELSE statement Perl conditional statement

An unless statement can be followed by an optional else statement, which is executed when the Boolean expression is true.

Grammar

The syntax format looks like this:

unless(boolean_expression){
   # 在布尔表达式 boolean_expression 为 false 执行
}else{
   # 在布尔表达式 boolean_expression 为 true 执行
}

If the Boolean expression boolean_expression false, the code inside the unless block is executed. I f the Boolean expression is true, the code inside the else block is executed.

Flow chart

Perl UNLESS... ELSE statement

Instance

#!/usr/bin/perl

$a = 100;
# 使用 unless 语句检测布尔表达式
unless( $a == 20 ){
    # 布尔表达式为 false 时执行
    printf "给定的条件为 false\n";
}else{ 
    # 布尔表达式为 true 时执行
    printf "给定的条件为 true\n";
}
print "a 的值为 : $a\n";

$a = "";
# 使用 unless 语句检测布尔表达式
unless( $a ){
    # 布尔表达式为 false 时执行
    printf "a 给定的条件为 false\n";
}else{
   # 布尔表达式为 true 时执行
    printf "a 给定的条件为 true\n";
}
print "a 的值为 : $a\n";

The above procedure is performed and the output is:

给定的条件为 false
a 的值为 : 100
a 给定的条件为 false
a 的值为 : 

Perl UNLESS... ELSE statement Perl conditional statement