David B
David B

Reputation: 29988

How can I check if a value is undef in Perl?

Best asked by an example:

my $var1=1;
my $var2;
my $var3=3;

# say "at least one undef" if at least one of $var1, $var2, $var3 is undef

Obviously I can explicitly loop and do that, but I always like to find one liners that achieve the same result.

Upvotes: 3

Views: 1677

Answers (2)

erickb
erickb

Reputation: 6309

expanding on Bob's answer, in some cases, you might want to grab the actual count

say 'has ', scalar ( grep { not defined } $var1,$var2,$var3 ),' undef';

Upvotes: 1

Bob
Bob

Reputation: 116

if (grep { !defined } $var1, $var2, $var3) {
  say 'at least one undef'
}

one liner

say 'at least one undef' if grep { !defined } $var1, $var2, $var3;

Upvotes: 10

Related Questions