Removing the Last Line of a File
Problem
You’d like to remove the last line from a file.
Solution
Read the file a line at a time and keep track of the byte address of the last line you’ve seen. When you’ve exhausted the file, truncate to the last address you saved:
open (FH, "+< $file") or die "can't update $file: $!"; while ( <FH> ) { $addr = tell(FH) unless eof(FH); } truncate(FH, $addr) or die "can't truncate $file: $!";
Discussion
This is much more efficient than reading the file into memory all at once, since it only holds one line at a time. Although you still have to grope your way through the whole file, you can use this program on files larger than available memory.
See Also
The open
and binmode
functions
in perlfunc
(1) and in Chapter 3 of
Programming Perl; your system’s
open
(2) and fopen
(3)
manpages
Get Perl Cookbook now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.