jms53 if the loop goes like this you try to print your data structure using Data::Dumper module, so that you can get understand how the data get saved.
I didn't see the structure any different from what I was expecting in Data::Dumper, although that is likely to be my lack of experience with Data::Dumper.
Athanasius's correction to the sub made everything work as expected.