有没有办法用更好的东西替换Perl中的if-elsif-else?

时间:2011-11-29 22:06:22

标签: perl design-patterns perl-module perl-data-structures

我想构建一堆Perl子程序,它们都具有相同的模板if elsif elsif else,它根据因子变量做出决定。这是子程序模板的一个例子:

sub get_age{

  my $factor=shift;

  if    ($factor == 1 ){ print "do something" }
  elsif ($factor == 2 ){ print "do somthing2" }
  elsif ($factor == 3 ){ print "do somthing3" }
  elsif ($factor == 4 ){ print "do somthing4" }
  else                 { print "error"        }
  }

我想知道Perl上是否有一些设计模式用更优雅的解决方案替换if else条件,如果我需要更改某些条件或删除其中某些条件,将来是否容易维护? / p>

7 个答案:

答案 0 :(得分:10)

有几个人提到了调度表。有两件事情,有时让它们分开是件好事。有可能发生的事情列表,以及使它们发生的事情。如果你把两者结合起来,你就会坚持使用你的解决方案。如果将它们分开,以后会有更大的灵活性。

dispatch表将行为指定为数据而不是程序结构。这有两种不同的方法。在你的例子中,你有整数和类似的东西可能使用数组来存储东西。哈希示例是相同的想法,但略微不同地查找行为。

另请注意,我将print分解出来。如果您重复这样的代码,请尝试将重复的内容移动到某个级别。

use v5.10;

foreach my $factor ( map { int rand 5 } 0 .. 9 ) {
    say get_age_array( $factor );
    }

my @animals = qw( cat dog bird frog );
foreach my $factor ( map { $animals[ rand @animals ] } 0 .. 9 ) {
    say get_age_hash( $factor );
    }

sub get_age_array {
    my $factor = shift;

    state $dispatch = [
        sub { 'Nothing!' }, # index 0
        sub { "Calling 1" },
        sub { 1 + 1 },
        sub { "Called 3" },
        sub { time },
        ];

    return unless int $factor <= $#$dispatch;

    $dispatch->[$factor]->();   
    }


sub get_age_hash {
    my $factor = shift;

    state $dispatch = {
        'cat'  => sub { "Called cat" },
        'dog'  => sub { "Calling 1"  },
        'bird' => sub { "Calling 2, with extra" },
        };

    return unless exists $dispatch->{$factor};

    $dispatch->{$factor}->();   
    }

答案 1 :(得分:7)

更新:请务必阅读以下brian的评论;基本上,由于他在链接中发表的各种问题,最好使用for代替given。我已经更新了我的建议以纳入他的改进,他在Use for() instead of given()中概述了:

如果您使用的是perl 5.10或更高版本,given/when是您正在寻找的神奇对,但您确实应该使用for/when代替..以下是一个示例:

use strict;
use warnings;
use feature qw(switch say);

print 'Enter your grade: ';
chomp( my $grade = <> );

for ($grade) {
    when ('A') { say 'Well done!'       }
    when ('B') { say 'Try harder!'      }
    when ('C') { say 'You need help!!!' }
    default { say 'You are just making it up!' }
}

答案 2 :(得分:3)

只是缩短时间:

sub get_age1 {
    my $age = shift;
    $age == 1 ? print "do something" :
    $age == 2 ? print "do somthing2" :
    $age == 3 ? print "do somthing3" :
    $age == 4 ? print "do somthing4" :
                print "error"
}
如果条件可以最好地表达为正则表达式,那么这个更有意义:

sub get_age2 {    
    for (shift) { 
        if    (/^ 1 $/x) {print "do something"}
        elsif (/^ 2 $/x) {print "do somthing2"}
        elsif (/^ 3 $/x) {print "do somthing3"}
        elsif (/^ 4 $/x) {print "do somthing4"}
        else             {print "error"       }
    }
}

这里有几个调度表:

简单的(带有错误):

{
    my %age = ( # defined at runtime
        1 => sub {print "do something"},
        2 => sub {print "do somthing2"},
        3 => sub {print "do somthing3"},
        4 => sub {print "do somthing4"},
    );
    # unsafe to call get_age3() before sub definition
    sub get_age3 {
        ($age{$_[0]} or sub {print "error"})->()
    }
}

更好的一个:

{
    my %age;
    BEGIN {
        %age = ( # defined at compile time
            1 => sub {print "do something"},
            2 => sub {print "do somthing2"},
            3 => sub {print "do somthing3"},
            4 => sub {print "do somthing4"},
        )
    }
    # safe to call get_age4() before sub definition
    sub get_age4 {
        ($age{$_[0]} or sub {print "error"})->()
    }
}

另一种写作方式:

BEGIN {
    my %age = ( # defined at compile time
        1 => sub {print "do something"},
        2 => sub {print "do somthing2"},
        3 => sub {print "do somthing3"},
        4 => sub {print "do somthing4"},
    );
    # safe to call get_age5() before sub definition
    sub get_age5 {
        ($age{$_[0]} or sub {print "error"})->()
    }
}

另一种写它的好方法:

{
    my $age;
    # safe to call get_age6() before sub definition
    sub get_age6 {
        $age ||= { # defined once when first called
           1 => sub {print "do something"},
           2 => sub {print "do somthing2"},
           3 => sub {print "do somthing3"},
           4 => sub {print "do somthing4"},
        };
        ($$age{$_[0]} or sub {print "error"})->()
    }
}

答案 3 :(得分:0)

调度表非常适合此类设计模式。我多次使用这个成语。像这样:

sub get_age {
    my $facter = shift;
    my %lookup_map = (
        1 => sub {.....},
        2 => sub {.....},
        3 => \&some_other_sub,
        default => \&some_default_sub,
    );
    my $code_ref = $lookup_map{$facter} || $lookup_map{default};
    my $return_value = $code_ref->();
    return $return_value;
}

当您用于确定执行哪个案例的参数将作为哈希表中的键存在时,此方法有效。如果它可能不是完全匹配,那么您可能需要使用正则表达式或其他方式来匹配您的输入以执行哪些代码。您可以使用正则表达式作为哈希键,如下所示:

my %patterns = (
    qr{^/this/one}i => sub {....},
    qr{^/that/one}is => sub {....},
    qr{some-other-match/\d+}i => \&some_other_match,
)
my $code_ref;
for my $regex (keys %patterns) {
    if ($facter =~ $regex) {
        $code_ref = $patterns{$regex};
        last;
    }
}
$code_ref ||= \&default_code_ref;
$code_ref->();

答案 4 :(得分:0)

请参阅示例/参考/dispatch_table.pl

https://code-maven.com/slides/perl/dispatch-table

#!/usr/bin/perl
use strict;
use warnings;

# Use subroutine references in a hash to define what to do for each case

my %dispatch_table = (
    '+' => \&add,
    '*' => \&multiply,
    '3' => \&do_something_3,
    '4' => \&do_something_4,
);

foreach my $operation ('+', 'blabla', 'foobar', '*'){
    $dispatch_table{$operation}->(
        var1 => 5,
        var2 => 7,
        var3 => 9,                       
    ) if ( exists $dispatch_table{$operation} );
}

sub add {
    my %args = (@_);
    my $var1 = $args{var1}; 
    my $var2 = $args{var2};

    my $sum = $var1 + $var2;
    print "sum = $sum \n";
    return;
}

sub multiply {
    my %args = (@_);
    my $var1 = $args{var1}; 
    my $var3 = $args{var3};

    my $mult = $var1 * $var3;
    print "mult = $mult \n";
    return;
}

输出:

sum = 12 
mult = 45 

答案 5 :(得分:-1)

这可能是一个像调度表这样的地方。我自己没有这样做,但这个页面可能是一个开始:http://www.perlmonks.org/?node_id=456530

答案 6 :(得分:-4)

使用Switch;

高阶Perl 中阅读Dispatch Tables