in reply to what is the best method to read and write in a file in perl
What is the issue ?
The issue is that you're in overwrite mode not insert mode. :)
This may make things clearer. (~ represent newlines).:
1~2~3~4~5~ ## Old contents 1~2~two~hi hello~ ## New contents.
I'm guessing that it was your intent to replace the '2' with 'two', but as you'd just read the '2' from the file, the file pointer was already pointing at the '3', so that where it started writing.
And because what you wrote was longer than what is there, you overwrote everything beyond the point where you started.
To understand what you would need to do in order to achieve what you set out to achieve, put you console into overwrite mode, type the original contents (on one line with '~'s as above. Then back up to the point you want to replace and start typing. (Without setting insert mode on, because files don't have an insert mode.)
Then forget the idea and do as moritz suggested.
|
|---|