首先,我意识到我可以用这个编译和运行的运算符编写一个if语句。我想知道是否有一种方法可以用来使if
/ elsif
/ else
块更优雅。
我目前有一块看起来像这样的代码
if( $bill == $ted) {
# Do some stuff
} elsif( $bill < $ted) {
# Do different stuff
} else {
# Do really weird stuff
}
因此,根据两个值是否相等,或者它们是否相等,无论哪个值较低,我都希望脚本执行特定的操作。似乎<=>
运营商将非常适合这一点。
好吧,操作符返回1,0或-1,具体取决于测试结果,这是sort
使用的。
所以这样做很可行。但与此相比,我不确定这是否是一种特别明确的方法;
if ( $first < $second ) { do X ; next}
if ( $first > $second ) { do Y ; next}
do Z. #$first == $second
我强烈建议避免使用单字母变量名,尤其是$a
和$b
。这是一种糟糕的风格,$a
使用$b
和sort
,这可能导致混乱。
这有点模糊,但您可以使用<=>
运算符来获取调度表的元素:
( 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 }->();
这使用<=>
的结果作为像choroba的答案的数组索引,但是没有必要存储和调用匿名子例程
我仍然不会在实时代码中使用它
use strict;
use warnings;
use feature 'say';
for my $x ( 1 .. 3 ) {
say ['equal', 'greater than', 'less than']->[$x <=> 2];
}
less than
equal
greater than
我不会称之为优雅,但您可以使用给定/何时捕获所有结果:
use strict;
use 5.10.0;
use feature "switch";
use experimental "smartmatch";
my $x = 1;
given( $x <=> 2 ){
when(-1){
say "stuff"
}
when(0){
say "diff stuff"
}
when(1){
say "other stuff"
}
}
从没有实验特征的draxil中得到启示:
use strict;
use warnings;
my $x = 1;
for ( $x <=> 2 ){
if ($_ == -1){
say "stuff"
}
if ($_ == 0){
say "diff stuff"
}
if ($_ == 1){
say "other stuff"
}
}
{
goto (qw( EQ GT LS ))[$x <=> $y];
LS:
say('less');
last;
EQ:
say('equal');
last;
GT:
say('greater');
}
But:
如果您正在优化可维护性,则不一定建议这样做。