in reply to Possible to refer to variable defined later in script?
Or, you could rearrange the code to write to the file AFTER you figured out what to write.