in reply to replace middle spaces and write to another file

Each line ends with a newline, and newline is a form of whitespace (/\s/). Either chomp off the line endings and add them back when you output, or be more selective in what you replace (i.e. match / /, /\t/ or /[ \t]/ instead of /\s/).

Update: Sorry, this is effectively a duplicate of the earlier post which I somehow missed.