Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if several variables are empty in Perl

Tags:

variables

perl

I have a Perl script where variables must be initialized before the script can proceed. A lengthy if statement where I check each variable is the obvious choice. But maybe there is a more elegant or concise way to check several variables.

Edit: I don't need to check for "defined", they are always defined with an empty string, I need to check that all are non-empty.

Example:

my ($a, $b, $c) = ("", "", "");

# If-clauses for setting the variables here

if( !$a || !$b || !$c) {
  print "Init failed\n";
}
like image 647
chiborg Avatar asked Nov 27 '22 03:11

chiborg


1 Answers

I am assuming that empty means the empty string, not just any false value. That is, if 0 or "0" are ever valid values post-initialization, the currently accepted answer will give you the wrong result:

use strict; use warnings;

my ($x, $y, $z) = ('0') x 3;
# my ($x, $y, $z) = ('') x 3;

for my $var ($x, $y, $z) {
    die "Not properly initialized\n" unless defined($var) and length $var;
}

Now, this is pretty useless as a validation, because, more than likely, you would like to know which variable was not properly initialized if this situation occurs.

You would be better served by keeping your configuration parameters in a hash so you can easily check which ones were properly initialized.

use strict; use warnings;

my %params = (
    x => 0,
    y => '',
    z => undef,
);

while ( my ($k, $v) = each %params ) {
    validate_nonempty($v)
        or die "'$k' was not properly initialized\n";
}

sub validate_nonempty {
    my ($v) = @_;
    defined($v) and length $v;
}

Or, if you want to list all that were not properly initialized:

my @invalid = grep is_not_initialized($params{$_}), keys %params;
die "Not properly initialized: @invalid\n" if @invalid;

sub is_not_initialized {
    my ($v) = @_;
    not ( defined($v) and length $v );
}
like image 68
Sinan Ünür Avatar answered Dec 17 '22 04:12

Sinan Ünür