So, i have a few variables that i need to check for emptyness, and it would be nicer and easier if i could do it in some way other than comparing each and every one like this
if ($var1 ne "" && $var2 ne "" && $var3 ne"")
So is there a better way?
PS: If anybody is going to propose to put them in a hash and loop through them, they are already in a hash, but they're not alone there, i have a lot of other values there(all are needed together later in the code, so spliting it wouldn't be easy).
You could make use of List::Util::all
like this
use List::Util 'all';
if ( all { $_ ne '' } $var1, $var2, $var3 ) { ... }
but I would expect to see it in the form you show
If you are testing the values of a hash then you should use a hash slice to select them
if ( all { $_ ne '' } @hash{@keys_to_check} ) { ... }
If they're in a hash, you can access them as a slice and grep them:
Something like this:
#!/usr/local/bin/perl
use strict;
use warnings;
my %hash = (
"to_test" => "",
"to_ignore" => "some value",
"also_to_test" => "",
"not_to_test" => "content here",
);
my @keys = qw ( to_test also_to_test );
unless ( grep { $_ ne '' } @hash{@keys} ) {
print "Keys are all empty: @keys\n";
}
You could do a similar thing with named variables, but that's perhaps not quite as elegant.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With