in reply to Brackets are driving me insane....

Ya forgot one! =)
print NDAT "$one"; } else { print NDAT $INPUT{"q$i-a$j"}; print NDAT "\n"; } # oops! }

Close the if, close the inner foreach, close the outer foreach, close the subroutine. As to the other problem, we'll need more info--like environment, the first few lines of your program, how it's being called, etc.