I have a data structure that features an array with preallocated slots ("empty slots").
Writing a print routine, I wonder how I can make a difference between an "empty slot" and a slot that has undef value.
The Perl debugger can do that, but I don't know how it detects the difference.
Example:
DB<10> $r = []
DB<11> $#$r=4
DB<12> $r->[4]=undef
DB<13> x $r
0 ARRAY(0x55d8fa6797e8)
0 empty slot
1 empty slot
2 empty slot
3 empty slot
4 undef
empty slot refers to a scalar that doesn't exist (NULL pointer, in C terms), while undef refers to one that exists but isn't defined (a pointer to a scalar that contains no values).
exists can be used to determine if the value an element exists or not. (It will also return true for elements outside of the arrays bounds.)
defined can be used to determine if an element is defined or not. (It will also return true for elements outside of the array's bounds and for elements with non-existent values.)
Please don't use exists on array elements. Code relying on identifying whether an elements exists or not will be less readable and less maintainable code than alternatives. The docs say it's not even reliable:
WARNING: Calling exists on array values is strongly discouraged. The notion of deleting or checking the existence of Perl array elements is not conceptually coherent, and can lead to surprising behavior.
use feature qw( say );
sub info {
my ($a, $i) = @_;
if ( $i >= @$a ) { say "$i: Non-existent slot" }
if ( !exists($a->[$i]) ) { say "$i: Non-existent scalar" }
if ( !defined($a->[$i]) ) { say "$i: Undefined" }
if ( !$a->[$i] ) { say "$i: False" }
if ( $a->[$i] ) { say "$i: True" }
say "";
}
my @a;
$a[1] = undef;
$a[2] = 0;
$a[3] = 1;
info(\@a, $_) for 4,0..3;
Output
4: Non-existent slot
4: Non-existent scalar
4: Undefined
4: False
0: Non-existent scalar
0: Undefined
0: False
1: Undefined
1: False
2: False
3: True
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With