Hello Monks,
I know this title sounds like a very common issue, but I came here to seek your wisdom on my observation. I have a script that processes some values and then stores them into an array.
While I was trying to observe if the array contains element(s) I found several tutorials and documentation online that should work, such as exists, defined, How do I test if an array is empty or not? etc.
I created a small demonstration script to replicate my curiosity question.
#!/usr/bin/perl use strict; use warnings; use Data::Dumper; my @a = (); my @b = ( undef ); print "\@a is not Empty\n" if (@a); print "\@b is not Empty\n" if (@b); print "\@a is not Empty grep\n" if grep { defined($_) } @a; print "\@b is not Empty grep\n" if grep { defined($_) } @b; print Dumper \@a; print Dumper \@b;
Sample of output:
@b is not Empty $VAR1 = []; $VAR1 = [ undef ];
Now that I am thinking about it more, still undef it occupies a position on the array. Possibly this is the reason that if (@b) still prints the text.
From my point of view in cases that a script can contain undef values someone should use the if grep { defined($_) } @b functionality to determine if the array is empty, alternatively a simple if condition should do the work.
Can someone provide a bit of more information regarding undef. Thank you in advance for your time and effort.
In reply to How to determine if an array contains an undef value? by thanos1983
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |