Skip to content

Latest commit

 

History

History
63 lines (54 loc) · 1.55 KB

16.md

File metadata and controls

63 lines (54 loc) · 1.55 KB

perl 中的if-elsif-else语句

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

当我们需要检查多个条件时使用if-elsif-else语句。在这个声明中,我们只有一个if和一个else,但是我们可以有多个elsif。这是它的样子:

if(condition_1) {
   #if condition_1 is true execute this
   statement(s);
}
elsif(condition_2) {
   #execute this if condition_1 is not met and
   #condition_2 is met
   statement(s);
}
elsif(condition_3) {
   #execute this if condition_1 & condition_2 are
   #not met and condition_3 is met
   statement(s);
}
.
.
.
else {
   #if none of the condition is true
   #then these statements gets executed
   statement(s);
}

注意:这里需要注意的最重要的一点是,在if-elsif-else语句中,只要满足条件,就会执行相应的语句集,忽略其余。如果没有满足条件,则执行else内的语句。

例:

#!/usr/local/bin/perl

printf "Enter any integer between 1 & 99999:";
$num = <STDIN>;
if( $num <100 && $num>=1) {
   printf "Its a two digit number\n";
}
elsif( $num <1000 && $num>=100) {
   printf "Its a three digit number\n";
}
elsif( $num <10000 && $num>=1000) {
   printf "Its a four digit number\n";
}
elsif( $num <100000 && $num>=10000) {
   printf "Its a five digit number\n";
}
else {
   printf "Please enter number between 1 & 99999\n";
}

输出:

Enter any integer between 1 & 99999:8019
Its a four digit number