perl 沒有提供 switch 控制結構功能,下列方式可以使 perl 有 switch 控制結構的功能。

方法 1:使用 LABEL
SWITCH: {
    if (/^abc/) { $abc = 1; last SWITCH; }
    if (/^def/) { $def = 1; last SWITCH; }
    if (/^xyz/) { $xyz = 1; last SWITCH; }
    $nothing = 1;
}

SWITCH: {
    $abc = 1, last SWITCH if /^abc/;
    $def = 1, last SWITCH if /^def/;
    $xyz = 1, last SWITCH if /^xyz/;
    $nothing = 1;
}

SWITCH: {
    /^abc/ && do { $abc = 1; last SWITCH; }
    /^def/ && do { $def = 1; last SWITCH; }
    /^xyz/ && do { $xyz = 1; last SWITCH; }
    $nothing = 1;
}

方法 2:使用 feature module
use feature "switch";
given($_) {
    when (/^abc/) { $abc = 1; }
    when (/^def/) { $def = 1; }
    when (/^xyz/) { $xyz = 1; }
    default { $nothing = 1; }
}

方法 3:使用 Switch module
use Switch;
switch ($value) {
    case 17         { print "number 17"       }
    case "snipe"    { print "a snipe"         }
    case /[a-f]+/i  { print "pattern matched" }
    case [1..10,42] { print "in the list"     }
    case (@array)   { print "in the array"    }
    case (%hash)    { print "in the hash"     }
    else            { print "no case applies" }
}

如果判斷條件需要重複動作,則須加 next :
%traits = (pride => 2, sloth => 3, hope => 14);
switch (%traits) {
    case "impatience"                   { print "Hurry up!\n";       next }
    case ["laziness","sloth"]           { print "Maybe tomorrow!\n"; next }
    case ["hubris","pride"]             { print "Mine's best!\n";    next }
    case ["greed","cupidity","avarice"] { print "More more more!";   next }
} 

或使用 fall-through 模式:
use Switch 'fallthrough';
%traits = (pride => 2, sloth => 3, hope => 14);
switch (%traits) {
    case "impatience"                   { print "Hurry up!\n"       }
    case ["laziness","sloth"]           { print "Maybe tomorrow!\n" }
    case ["hubris","pride"]             { print "Mine's best!\n"    }
    case ["greed","cupidity","avarice"] { print "More more more!"   }
}

搗蛋鬼 發表在 痞客邦 PIXNET 留言(0) 人氣()