是否可以在 perl 中的 'eq' 或 'ne' 比较中使用 'or' 或 'and' 运算符?

Is it possible to have an 'or' or 'and' operator inside an 'eq' or 'ne' comparison in perl?

是否可以缩短这个场景:

use strict;
use warnings;

my $tests = [-1,0,1,2,];

foreach my $test (@$tests){
    if ($test ne 0 and $test ne -1){ # THIS LINE
       print "$test - Success\n";
    }else{
       print "$test - Error\n";
    }
}

输出:

-1 - Error
0 - Error
1 - Success
2 - Success

进入类似的东西,你可以在比较语句中放置一组条件(我知道这段代码不起作用,是我正在搜索的类似语法的一个例子):

use strict;
use warnings;

my $tests = [-1,0,1,2,];

foreach my $test (@$tests){
    if ($test ne (-1 or 0) ){ # THIS LINE
       print "$test - Success\n";
    }else{
       print "$test - Error\n";
    }
}

用例是这样的

foreach my $i (0..$variable){
    test 1
    if ($test->{a}->{$variable}->{b} ne 1 and $test->{a}->{$variable}->{b} ne 0){
        ...
    }
    # test 2
    if ($test->{a}->{$variable}->{c} ne 3 and $test->{a}->{$variable}->{c} ne 4){
        ...
    }
}

像这样的某些语法会大大简化此类测试的编写,而无需创建新变量以使代码易于阅读。

我会使用 List::Util::any or List::Util::all:

if (any { $test != $_ } 0, 1) { ... }
if (all { $test != $_ } 0, 1) { ... }

类似于

if ($test != 0 || $test != 1) { ... }
if ($test != 0 && $test != 1) { ... }

请注意 List::Util 是核心模块,这意味着您无需安装任何东西即可使用。只需将 use List::Util qw(any all) 添加到您的脚本中即可。