in reply to problem with variable scoping

I do not get your symptoms, $i was 0 first time around, then 1, then 0, then 1. However %ref_to_msg_defs was not defined, and the prototype you have in sub populatemessagedefs() means 'no parameters', which is probably not what you want. But I don't think that will cause your problem.