in reply to $#{$array_ref} changes in loop

As others have noted, you ran into auto-vivification. I was bit by the same thing not too long ago, and ferreira provided a great example with several links to discussions of the issue.

Hopefully these nodes will help you as they did me.