After trying several options, I must admit that I coudn't
find the reason for it not working as it should.
The only thing that might help is - only in case the
file is relatively small - reading all the file contents
into an array (@lines = <FILE>), writing the required data
while file is...