if语句中的Eval

sac*_*hin 1 perl

如何在perl if语句中动态传递eq或ne?我在下面尝试但是没有工作:

my $this="this";
my $that="that";
my $cond='ne';
if($this eval($cond) $that)
{
  print "$cond\n";
}
Run Code Online (Sandbox Code Playgroud)

Eug*_*ash 9

你不需要eval这个.只需使用调度表:

sub test {
    my %op = (
        eq => sub { $_[0] eq $_[1] },
        ne => sub { $_[0] ne $_[1] },
    );
    return $op{ $_[2] }->($_[0], $_[1]);        
}

if (test($this, $that, $cond)){
    print "$cond\n";
}
Run Code Online (Sandbox Code Playgroud)

  • 很好,但是这个解决方案会在每次调用test()时生成一组_different_匿名子(或者说是闭包). (2认同)

Dal*_*aen 7

if (($cond eq 'eq') xor ($this ne $that)) {
     print $cond;
};
Run Code Online (Sandbox Code Playgroud)

但也许更好,更通用的方法是使用perl的功能并创建函数的哈希表:

my %compare = (
     eq => sub {shift eq shift},
     ne => sub {shift ne shift},
     lt => sub {shift lt shift},
     like => sub {$_[0] =~ /$_[1]/},
     # ....
);

#...
if ($compare{$cond}->($this, $that)) {
     print $cond;
};
Run Code Online (Sandbox Code Playgroud)