簡體   English   中英

為什么開關不起作用?

[英]Why switch doesn't work?

該程序拋出錯誤。 問題是我必須使用switch case 我如何在Perl中做到這一點?

#use strict;
#use warnings;
my $input = print "Enter the number";
$input = <STDIN>;
switch($input){
    case "1" {print "UPC"}
    case "2" {print "ES"}
    case "3" {print "MS"}
    else {print "Enter the correct value"}
}

Perl的case語句的內置版本略有不同:

use feature "switch";

given ($foo) {
        when (/^abc/) { $abc = 1; }
        when (/^def/) { $def = 1; }
        when (/^xyz/) { $xyz = 1; }
        default { $nothing = 1; }
    }

您可以use Switch;添加更傳統的case語句use Switch; ,但RobEarl指出,這已被棄用。

另外, 切勿評論use strict; use warnings; use strict; use warnings; 作為解決問題的嘗試!

您需要導入Switch才能使用它:

use Switch;

但是, 不推薦使用 Switch。 看到以下問題: 為什么在Perl中不推薦使用Switch模塊?

這里討論了一些替代方法(及其實驗狀態): http : //perldoc.perl.org/perlsyn.html#Switch-Statements

總之,如果您使用的是Perl> 5.10.1,則可以將以下內容用於不推薦使用的,非實驗性的開關:

use v5.10.1;
for ($var) {
    when (/^abc/) { $abc = 1 }
    when (/^def/) { $def = 1 }
    when (/^xyz/) { $xyz = 1 }
    default { $nothing = 1 }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM