Tip #1 from the
Basic debugging checklist is to
use diagnostics. This would have given you a couple of hints as to the specific problems with your misbehaving code, particularly to
look into how references work.
Tip #4 is also useful in visualizing your data structure, using Data::Dumper.