Reputation: 2221
Is it possible to shorten this scenario:
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";
}
}
Output:
-1 - Error
0 - Error
1 - Success
2 - Success
Into something similar to this where you can put a set of conditions inside the comparison statment (I know this code does not work, is an example of a similar syntax I am searching for):
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";
}
}
The use case would be something like this
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){
...
}
}
Some syntax like that would simplify a lot writing that type of tests without having to create new variables to make the code easy to read.
Upvotes: 3
Views: 305
Reputation: 6626
I'd use List::Util::any
or List::Util::all
:
if (any { $test != $_ } 0, 1) { ... }
if (all { $test != $_ } 0, 1) { ... }
is similar to
if ($test != 0 || $test != 1) { ... }
if ($test != 0 && $test != 1) { ... }
Note that List::Util
is a core module, which means that you don't have to install anything for this to work. Just add use List::Util qw(any all)
to your script.
Upvotes: 4