Another solution to this is to use splice and insert/remove lines from your file. This involves you reading the whole file into an array (or into a scalar and calling split) and then writing the whole array back out again.
I notice that you skip on certain lines whilst moving about the array and printing it out. As long as you keep a track of the line index - the above method should work regardless.
I have used this method on a basic .htaccess file manager in the past with success. However, I would argue that it is only viable for a low usage system. I would also recommend that you consider making regular backups (you do do that? :P)