是否可以缩短这种情况:
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 - Successn";
}else{
print "$test - Errorn";
}
}
输出:
-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 - Successn";
}else{
print "$test - Errorn";
}
}
用例应该类似于这个
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
或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)
添加到脚本中即可。