开发者

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

开发者 https://www.devze.com 2023-01-17 06:44 出处:网络
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

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.


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

one liner

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


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';
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号