Skip to content

Latest commit

 

History

History
48 lines (39 loc) · 1.03 KB

21.md

File metadata and controls

48 lines (39 loc) · 1.03 KB

Perl 中的given-when-default语句

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

正如我在上一篇文章中所讨论的那样,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