I have not dissected your code, and do not know what is causing the problem you describe, but I have a couple of general comments.
- Add some vertical whitespace! You have what appears to be a good amount of comments, but it could really use some empty lines to break things up. It makes me dizzy to try and discern the logical chunks.
- Always check the return status of open -- even when opening a file for input. On a related note, in your die on the output file's open call, you do not include $! in the output string. This is often very helpful.
- Perhaps instead of using a global bareword filehandle, you could use a lexically scoped, autovivified filehandle, which you pass into your subroutines as a normal argument?
Here's a quick example demonstrating these points:
open my $fh, "<", $input or die "$input: $!";
foo($fh);
sub foo {
my ($fh) = @_;
my $line = <$fh>;
print $line;
}
Hopefully one of these suggestions will lead you to find the problem on your own.