微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

如何解决perl 中的“eq”或“ne”比较中是否可以使用“or”或“and”运算符?

是否可以缩短这个场景:

use strict;
use warnings;

my $tests = [-1,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,];

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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。