Aah another thing just noticed (after caffeine has put the mind in motion a bit) you've got an outer while loop reading your input FH handle as well as a nested foreach reading the same handle. You look to be effectively reading the first line and discarding it (after printing it to STDOUT), then reading the rest of the file. That's . . . probably not what you want and may be why you're out of sync.
As I mentioned, if you change things to do record reads (see perlvar for $/) and then have a single while reading input records once that may help keep things straight(er).
The cake is a lie.
The cake is a lie.
The cake is a lie.