Perl IF...ELSE 语句
Perl if 语句后面可以跟一个可选的else 语句,当布尔表达式为假时执行。
语法
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 对真值的否定返回一个特殊的假值。
流程图
示例
#!/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 :