如何在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)
你不需要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)
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)