Perl IF...ELSE 语句



一个 Perl if 语句可以紧随一个可选的 else 语句,它当布尔表达式为 false 时执行。

语法

Perl 编程语言中 if...else 语句的语法为 -

if(boolean_expression) {
   # statement(s) will execute if the given condition is true
} else {
   # statement(s) will execute if the given condition is false
}

如果布尔表达式计算为 true,则会执行 if 块代码,否则会执行 else 块代码。

数字 0、字符串 '0' 和 ""、空列表 () 和 undef 在布尔上下文中均为 false,所有其他值均为 true。通过 !not 求得的真值的否定结果返回一个特殊的 false 值。

流程图

Perl if...else statement

示例

#!/usr/local/bin/perl
 
$a = 100;
# check the boolean condition using if statement
if( $a < 20 ) {
   # if condition is true then print the following
   printf "a is less than 20\n";
} else { 
   # if condition is false then print the following
   printf "a is greater than 20\n";
}
print "value of a is : $a\n";

$a = "";
# check the boolean condition using if statement
if( $a ) {
   # if condition is true then print the following
   printf "a has a true value\n";
} else {
   # if condition is false then print the following
   printf "a has a false value\n";
}
print "value of a is : $a\n";

当执行以上代码时,会产生以下结果 -

a is greater than 20
value of a is : 100
a has a false value
value of a is : 
perl_conditions.htm
广告
© . All rights reserved.