You're attempting to simultaneously read and write to the same file. That's not going to work real well. What you need to do is something along the lines of
- open the original file and seek to the end
- seek backwards the amount of data you want to keep (probably seeking back further and then reading forward to find the next full line/record; or use something like Tie::File)
- read those lines and write them into a new temporary file
- rename the temporary file to the original file's name