How do I change, delete, or insert a line in a file, or append to the beginning of a file? O and the “f” issues: filehandles, flushing, formats, and footers. Perl normally buffers output so it doesn’t make a system call option binary tree every bit of output.
By saving up output, it makes fewer expensive system calls. For instance, in this little bit of code, you want to print a dot to the screen for every line you process to watch the progress of your program. For more information on output layers, see the entries for binmode and open in perlfunc, and the PerlIO module documentation. The basic idea of inserting, changing, or deleting a line from a text file involves reading and printing the file to the point you want to make the change, making the change, then reading and printing the rest of the file. Within that basic form, add the parts that you need to insert, change, or delete lines. To prepend lines to the beginning, print those lines before you enter the loop that prints the existing lines. To change existing lines, insert the code to modify the lines inside the while loop.
In this case, the code finds all lowercased versions of “perl” and uppercases them. The happens for every line, so be sure that you’re supposed to do that on every line! First read and print the lines up to the one you want to change. Next, read the single line you want to change, change it, and print it. To skip lines, use the looping controls. The next in this example skips comment lines, and the last stops all processing once it encounters either __END__ or __DATA__ .
Do the same sort of thing to delete a particular line by using next to skip the lines you don’t want to show up in the output. Modules such as Path::Tiny and Tie::File can help with that too. If you can, however, avoid reading the entire file at once. Perl won’t give that memory back to the operating system until the process finishes. You can also use Perl one-liners to modify a file in-place. To delete lines, only print the ones that you want. How do I count the number of lines in a file?
Those can be rather inefficient though. However, that doesn’t work if the line ending isn’t a newline. How do I delete the last N lines from a file? Most often, the real question is how you can delete the last N lines without making more than one pass over the file, or how to do it without a lot of copying. The easy concept is the hard reality when you might have millions of lines in your file. That module provides an object that wraps the real filehandle to make it easy for you to move around the file.