有没有办法在perl if语句中使用<=>运算符?

Ger*_*ton 3 perl if-statement

首先,我意识到我可以用这个编译和运行的运算符编写一个if语句.我想知道是否有一种方法可以使if/ elsif/ else块更优雅.

我目前有一块看起来像这样的代码

 if( $bill == $ted) {
        # Do some stuff
} elsif( $bill < $ted) {
        # Do different stuff
} else {
        # Do really weird stuff
}
Run Code Online (Sandbox Code Playgroud)

因此,根据两个值是否相等,或者它们是否相等,无论哪个值较低,我都希望脚本执行特定的操作.看起来<=>运营商很适合这个.

cho*_*oba 6

这有点模糊,但您可以使用<=>运算符来获取调度表的元素:

(   sub { say 'they are the same' },
    sub { say 'x is greater' },
    sub { say 'x is lesser' }
)[$x <=> $y]->();
Run Code Online (Sandbox Code Playgroud)

它基于以下事实:索引-1返回列表的最后一个元素.

使用哈希可能更具可读性.

{    0 => sub { say 'they are the same' },
     1 => sub { say 'x is greater' },
    -1 => sub { say 'x is lesser' }
}->{ $x <=> $y }->();
Run Code Online (Sandbox Code Playgroud)

  • 技术上是正确的,但我想我会给那些在生产代码中做到这一点的人一个非常困难的时间. (7认同)
  • 聪明.也许太聪明了? (2认同)
  • @GernBlanston即使从性能的角度来看,这种"优化"也很可能是不值得的:子程序调用往往比简单的操作(例如(非重载)比较或if语句)要贵得多.我敢打赌,你问题中的代码已经是最快的,其次是tjd的for-if伪开关. (2认同)