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

问题描述 投票:3回答:6

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

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

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

因此,根据两个值是否相等,或者它们是否相等,无论哪个值较低,我都希望脚本执行特定的操作。似乎<=>运营商将非常适合这一点。

perl if-statement
6个回答
0
投票

好吧,操作符返回1,0或-1,具体取决于测试结果,这是sort使用的。

所以这样做很可行。但与此相比,我不确定这是否是一种特别明确的方法;

if ( $first < $second ) { do X ; next}
if ( $first > $second ) { do Y ; next}
do Z. #$first == $second

我强烈建议避免使用单字母变量名,尤其是$a$b。这是一种糟糕的风格,$a使用$bsort,这可能导致混乱。


6
投票

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

(   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 }->();

2
投票

这使用<=>的结果作为像choroba的答案的数组索引,但是没有必要存储和调用匿名子例程

我仍然不会在实时代码中使用它

use strict;
use warnings;
use feature 'say';

for my $x ( 1 .. 3 ) {
    say ['equal', 'greater than', 'less than']->[$x <=> 2];
}

output

less than
equal
greater than

0
投票

我不会称之为优雅,但您可以使用给定/何时捕获所有结果:

    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"
        }
    }

0
投票

从没有实验特征的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"
    }
}

0
投票
{
    goto (qw( EQ GT LS ))[$x <=> $y];
    LS:
        say('less');
        last;
    EQ:
        say('equal');
        last;
    GT:
        say('greater');
}

But

如果您正在优化可维护性,则不一定建议这样做。

© www.soinside.com 2019 - 2024. All rights reserved.