ThinkChat2.0新版上线,更智能更精彩,支持会话、画图、阅读、搜索等,送10W Token,即刻开启你的AI之旅 广告
# Perl 中的`if`语句 > 原文: [https://beginnersbook.com/2017/02/if-statement-in-perl/](https://beginnersbook.com/2017/02/if-statement-in-perl/) `if`语句包含条件,后跟一个语句或一组语句,如下所示: ```perl if(condition){ Statement(s); } ``` 只有在给定条件为真时才会执行语句。如果条件为`false`,那么`if`语句体内的语句将被完全忽略。 #### 例: 在以下示例中,我们将一个整数值赋给变量`num`。使用`if`语句,我们检查分配给`num`的值是否小于 100。 ```perl #!/usr/local/bin/perl printf "Enter any number:"; $num = <STDIN>; if( $num < 100 ){ # This print statement would execute, # if the above condition is true printf "num is less than 100\n"; } ``` **输出:** ```perl Enter any number:78 num is less than 100 ``` ## perl 中的嵌套`if`语句 当在另一个`if`语句中有`if`语句时,它将被称为嵌套`if`语句。 嵌套的结构如下所示: ```perl if(condition_1) { Statement1(s); if(condition_2) { Statement2(s); } } ``` 如果`condition_1`为`true`,则执行`Statement1`。只有条件(`condition_1`和`condition_2`)都为真时,`Statement2`才会执行。 #### 示例: ```perl #!/usr/local/bin/perl printf "Enter any number: "; $num = <STDIN>; if( $num < 100 ){ printf "num is less than 100\n"; if( $num > 90 ){ printf "num is greater than 90\n"; } } ``` **输出:** ```perl Enter any number: 99 num is less than 100 num is greater than 90 ```