If you provided a complete program and sample data that manifests the problem it would be easier to help. With only the fragments you have provided, one can only guess what might be causing the problem.

The console output you provide suggests that there might be unexpected carriage control characters in your output that cause your output to be written in unexpected, overlapping locations. When I have such problems I use the od command to examine the output in details, including non-printing characters (with od -c). This might help you identify what is going on.

When you look at the created file with a utility like 'more' or an editor, it probably looks fine. The funny characters are there, but the utility filters them in a way where you can see what you want to see. However, on the console, they aren't filtered for you.

Try adding $type=~s/[^[:print:]]/_/g; (before you print it) and see if any underscores start showing up in $type. That would indicate non-printables (backspaces, vertical tabs, etc) are in your data.