原文: https://beginnersbook.com/2017/02/if-statement-in-perl/

if语句包含条件,后跟一个语句或一组语句,如下所示:

  1. if(condition){
  2. Statement(s);
  3. }

只有在给定条件为真时才会执行语句。如果条件为false,那么if语句体内的语句将被完全忽略。

例:

在以下示例中,我们将一个整数值赋给变量num。使用if语句,我们检查分配给num的值是否小于 100。

  1. #!/usr/local/bin/perl
  2. printf "Enter any number:";
  3. $num = <STDIN>;
  4. if( $num < 100 ){
  5. # This print statement would execute,
  6. # if the above condition is true
  7. printf "num is less than 100\n";
  8. }

输出:

  1. Enter any number:78
  2. num is less than 100

perl 中的嵌套if语句

当在另一个if语句中有if语句时,它将被称为嵌套if语句。
嵌套的结构如下所示:

  1. if(condition_1) {
  2. Statement1(s);
  3. if(condition_2) {
  4. Statement2(s);
  5. }
  6. }

如果condition_1true,则执行Statement1。只有条件(condition_1condition_2)都为真时,Statement2才会执行。

示例:

  1. #!/usr/local/bin/perl
  2. printf "Enter any number: ";
  3. $num = <STDIN>;
  4. if( $num < 100 ){
  5. printf "num is less than 100\n";
  6. if( $num > 90 ){
  7. printf "num is greater than 90\n";
  8. }
  9. }

输出:

  1. Enter any number: 99
  2. num is less than 100
  3. num is greater than 90