perl - 有没有办法在 perl if 语句中使用 <=> 运算符?
问题描述
首先,我意识到我可以用这个运算符编写一个 if 语句来编译和运行。我想知道是否有一种方法可以用来使if
//块更优雅一点elsif
。else
我目前有一个看起来像这样的代码块
if( $bill == $ted) {
# Do some stuff
} elsif( $bill < $ted) {
# Do different stuff
} else {
# Do really weird stuff
}
因此,我希望脚本根据两个值是否相等或不相等(以较低者为准)来执行特定的操作。操作员似乎<=>
很适合这种情况。
解决方案
这有点晦涩,但您可以使用<=>
运算符来获取调度表的元素:
( 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 }->();
推荐阅读
- unity3d - 从外部文件夹实例化 3D 模型
- ios - RxSwift 中有没有办法观察数组内部的变化而不设置新值?
- javascript - 如何获得整个网页的高度?javascript
- node.js - 如何在等待/异步中返回承诺的价值,而不是承诺本身?
- php - 在 PHP Laravel 5.1 中验证必须包含字母、数字和特殊字符的密码
- javascript - 如何在javascript中搜索列表中的项目?
- python - 使用列表的 print 和 tkinter 文本框的不同输出
- java - ClassCast 异常:子类实现在调用超类方法时抛出异常
- reactjs - 不变违规:“borderLeft”不是有效的样式属性
- c++ - 键盘模拟器