To get more specific help, you should update your post with a small sample of your input files (a few lines each), your actual output and your expected output.

Probably unrelated to your problem... if you are interested in using a more robust (and modern) Perl coding style, run your code through perlcritic. Here are a few of the issues:

'Bareword file handle opened at line 37, column 2. See pages 202,204 +of PBP. (Severity: 5)',
'Two-argument "open" used at line 37, column 2. See page 207 of PBP. + (Severity: 5)',
'Close filehandles as soon as possible after opening them at line 37, +column 2. See page 209 of PBP. (Severity: 4)',
'"$nm" is declared but not used at line 27, column 1. Unused variable+s clutter code and make it harder to read. (Severity: 3)',
'Mismatched operator at line 53, column 21. Numeric/string operators +and operands should match. (Severity: 3)',