问题描述
是否可以缩短这个场景:
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::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)
添加到您的脚本中。