in reply to If condition logic yielding partially correct output

The problem is that you're comparing "test" numerically. "test" as a number is 0. 0 != 0 is false.

Assuming you don't want to print the key when it's undefined either, you could do:

print "\n$key\n" if $key;