【perl】perl实现case条件判断的语句

方法一: 5.8版本 使用Switch包

 use Switch;
        switch ($val) {
            case 1          { print "number 1" }
            case "a"        { print "string a" }
            case [1..10,42] { print "number in list" }
            case (@array)   { print "number in list" }
            case /\w+/      { print "pattern" }
            case qr/\w+/    { print "pattern" }
            case (%hash)    { print "entry in hash" }
            case (\%hash)   { print "entry in hash" }
            case (\&sub)    { print "arg to subroutine" }
            else            { print "previous case not true" }
        }

方法二:5.10版本

use 5.010;
given( $ARGV[0] ) {
    when( /fred/i ) { say 'Name has fred in it' }
    when( /^Fred/ ) { say 'Name starts with Fred' }
    when( 'Fred'  ) { say 'Name is Fred' }
    default         { say "I don't see a Fred" }
    }

 方法三:用hash做switch 和case (个人觉得最有趣的方法)

use strict;
use warnings;
my %subhash;
$subhash{a}=&a;
$subhash{b}=&b;
$subhash{c}=&c;
my $case = <STDIN>;
chomp $case;
&{$subhash{$case}};
sub a{print "a\n";}
sub b{print "b\n";}
sub c {print "c\n";}

原文地址:https://www.cnblogs.com/xianghang123/p/2355425.html