首页 > 解决方案 > 有没有办法在 perl if 语句中使用 <=> 运算符?

问题描述

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

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

 if( $bill == $ted) {
        # Do some stuff
} elsif( $bill < $ted) {
        # Do different stuff
} else {
        # Do really weird stuff
}

因此,我希望脚本根据两个值是否相等或不相等(以较低者为准)来执行特定的操作。操作员似乎<=>很适合这种情况。

标签: perlif-statement

解决方案


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

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

它基于索引 -1 返回列表的最后一个元素这一事实。

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

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

推荐阅读