原文: https://beginnersbook.com/2017/02/given-when-default-statement-in-perl/

正如我在上一篇文章中所讨论的那样,switch-case在 Perl 5 中被弃用。三个新关键字:given-when-default在 Perl 5 中引入,提供类似于switch case的功能。

语法:

  1. given (argument) {
  2. when (condition) { statement(s); }
  3. when (condition) { statement(s); }
  4. when (condition) { statement(s); }
  5. .
  6. .
  7. .
  8. default { statement(s); }
  9. }

例:

  1. #!/usr/local/bin/perl
  2. use v5.10;
  3. no warnings 'experimental';
  4. printf "Enter any number:";
  5. $num = <STDIN>;
  6. given($num){
  7. when ($num>10) {
  8. printf "number is greater than 10\n";
  9. }
  10. when ($num<10) {
  11. printf "number is less than 10\n";
  12. }
  13. default {
  14. printf "number is equal to 10\n";
  15. }
  16. }

输出:

  1. Enter any number:10
  2. number is equal to 10