3

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.

brian d foy
  • 129,424
  • 31
  • 207
  • 592
David B
  • 29,258
  • 50
  • 133
  • 186
  • possible duplicate of [How do I check if a Perl scalar variable has been initialized?](http://stackoverflow.com/questions/3738836/how-do-i-check-if-a-perl-scalar-variable-has-been-initialized) – brian d foy Sep 22 '10 at 13:47

2 Answers2

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

one liner

say 'at least one undef' if grep { !defined } $var1, $var2, $var3;
Bob
  • 116
  • 1
  • 2
  • `//` is a short-circuit operator, so it would be useful if you had a code path you want to execute conditionally based on the definedness of a single value. I can't think of a use here, but TMTOWTDI. – Bob Sep 22 '10 at 08:02
  • @David B, `//` is defined-or, so it can only be used to calculate "at least one defined". To get "at least one undef", you'd need a defined-and operator, which doesn't (currently) exist. – cjm Sep 22 '10 at 14:52
1

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';
erickb
  • 6,193
  • 4
  • 24
  • 19