开发者

can this perl code be simplified?

开发者 https://www.devze.com 2023-03-25 10:38 出处:网络
foreach my $f($query->param) { foreach my $v($query->param($f)) { switch($f) { case \'a\' { switch($v) {
foreach my $f($query->param) {
    foreach my $v($query->param($f)) {
        switch($f) {
            case 'a' {
                switch($v) {
                    case 1 { code1; }
                    case 2开发者_JS百科 { code2; }
                    case 3 { code3; }
                }

            case 'b' {
                switch($v) {
                    case 1 { code4; }
                    case 2 { code5; }
                }

            case 'c' {
                switch($v) {
                    case 1 { code6; }
                    case 2 { code7; }
                    case 3 { code8; }
                    case 4 { code9; }
                }
            }
        }
    }
}


Above all... DO NOT USE Switch.pm. If you are using Perl 5.10 or newer, given/when is a native switch statement.

A dispatch table is the solution you seek. http://www.perlmonks.org/?node_id=587072 describes dispatch tables, a technique for executing code via a hash based on some value matching the hash key.

Edit, example:

my %dispatch_table = (
    'a' => {
        '1' => sub { code1; },
        '2' => sub { code2; },
        '3' => sub { code3; },
    'b' => {
        '1' => \&some_sub,
        '2' => sub { code4; },
    }
)

if ( exists( $dispatch_table{$f} ) and exists( $dispatch_table{$f}{$v} ) ) {
    $dispatch_table{$f}{$v}->();
}
else {
    # some default
}


Put it in a "dispatch table":

my %code = (
    a => {
        1 => sub { code1 },
        2 => sub { code2 },
        3 => sub { code3 },
    },
    b => {
        1 => sub { code4 },
        2 => sub { code5 },
    },
    c => {
        1 => sub { code6 },
        2 => sub { code7 },
        3 => sub { code8 },
        4 => sub { code9 },
    },
);

Then once you have $f and $v, call the correct subroutine:

$code{$f}{$v}->();


Depending on what you mean by "simplified", you might consider something like this (if you're sure that neither $f nor $v can contain a ','):

foreach my $f ($query->param) {
    foreach my $v ($query->param($f)) {
        switch ("$f,$v") {
            case "a,1" { code; }
            case "a,2" { code; }
            case "a,3" { code; }

            case "b,1" { code; }
            case "b,2" { code; }

            case "c,1" { code; }
            case "c,2" { code; }
            case "c,3" { code; }
            case "c,4" { code; }
        }
    }   
}

(I'm assuming that all the occurrences of code; are actually different.)

0

精彩评论

暂无评论...
验证码 换一张
取 消