首先,我意识到我可以用这个编译和运行的运算符编写一个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)
因此,根据两个值是否相等,或者它们是否相等,无论哪个值较低,我都希望脚本执行特定的操作.看起来<=>运营商很适合这个.
这有点模糊,但您可以使用<=>运算符来获取调度表的元素:
( 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)