Reputation: 792
i have a code with many OR conditions like this (working fine) to check if one of the values is empty, then we throw an error message (all of them must be filled)
} elsif (
!$params{'account'}
|| !$params{'type'}
|| !$params{'sampledate'}
|| !$params{'lastpwchange'}
|| !$params{'system'}
|| !$params{'wspass'}
) {
print $cgi->header("text/plain"), "some mandatory parameters are missing";
}
i need to add many other variables in that condition, making the line a bit unreadable.
i was wondering if there was a more elegant way of specifying all of them, maybe using an array/list of some kind ?
thank you
Upvotes: 4
Views: 215
Reputation: 54323
You can use grep
to do that.
my %stuff = map { $_ => 1 } qw/ foo bar baz qrr qux asdf hello world /;
$stuff{foo} = 1; # toggle here
my $missing = grep { ! $stuff{$_} } qw/ foo bar baz qrr qux asdf hello world /;
print "missing argument" if $missing;
Upvotes: 5
Reputation: 222432
Using handy module List::Util
, you can do something like:
use List::Util qw/any/;
...
elsif (any { !$params{$_} } qw/account type sampledate lastpwchange system wspass/) {
print $cgi->header("text/plain"), "some mandatory parameters are missing";
}
Please note that your expression does not exactly checks for emptiness; it actually performs a boolean check, so a parameter having value 0
would also fail the check. This might, or might not be what you want.
Upvotes: 5