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

标签 perl compare operators

是否可以缩短这个场景:

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::anyList::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) 添加到您的脚本中即可。

关于perl - 是否可以在 perl 中的 'or' 或 'and' 比较中使用 'eq' 或 'ne' 运算符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67125513/

相关文章:

sql - select count(*) 不适用于 perl DBI

perl - 如何在 Perl 哈希表中存储多个值?

c++ - 内存比较(有差异位置)

C++:星号、符号和星号?

ruby-on-rails - ruby 是_a?对比===

php - 为什么 Perl DBI 在执行前需要准备语句?

Perl 和纪元时间问题

c# - 比较(JOIN)表并获取新记录

mysql - 如何在 MySQL 中按两列比较两个查询?

operators - 运算符 '<<' 和 '>>' 有什么作用?