in reply to calculate distance between atoms and a target atom

Your code does something like
if (X) { $Znx = ...; } elsif (Y) { $Znx = ...; }
If neither X nor Y is true, $Znx does not get assigned a value, so it remains undefined. Perl treats that as zero, which may or may not be what you want.