Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to compare multiple variables to the same value(empty) in Perl?

Tags:

perl

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).

like image 325
Adrian Todorov Avatar asked Dec 25 '22 17:12

Adrian Todorov


2 Answers

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} ) { ... }
like image 83
Borodin Avatar answered Dec 27 '22 10:12

Borodin


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.

like image 27
Sobrique Avatar answered Dec 27 '22 11:12

Sobrique