Perl 中的 given-when-default 语句,正如我在上一篇文章中所讨论的那样,switch-case
在 Perl 5 中被弃用。三个新关键字:given-when-default
在 Perl 5 中引入,提供类似于switch case
的功能。
语法:
given (argument) {
when (condition) { statement(s); }
when (condition) { statement(s); }
when (condition) { statement(s); }
.
.
.
default { statement(s); }
}
示例如下:
#!/usr/local/bin/perl
use v5.10;
no warnings 'experimental';
printf "Enter any number:";
num = <STDIN>;
given(num){
when (num>10) {
printf "number is greater than 10\n";
}
when (num<10) {
printf "number is less than 10\n";
}
default {
printf "number is equal to 10\n";
}
}
输出:
Enter any number:10
number is equal to 10