Perl IF... ELSE statement

Perl IF... ELSE statement Perl conditional statement

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

Grammar

The syntax format looks like this:

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

If the Boolean expression boolean_expression is true, the code within the if block is executed. If the Boolean expression is false, the code inside the else block is executed.

Flow chart

Perl IF... ELSE statement

Instance

#!/usr/bin/perl
 
$a = 100;
# 使用 if 语句判断布尔表达式
if( $a < 20 ){
    # 布尔表达式为true时执行
    printf "a 小于 20\n";
}else{ 
    # 布尔表达式为false时执行
    printf "a 大于 20\n";
}
print "a 的值为 : $a\n";

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

The above procedure is performed and the output is:

a 大于 20
a 的值为 : 100
a 条件为 false
a 的值为 :

Perl IF... ELSE statement Perl conditional statement