8.10. Removing the Last Line of a FileProblemYou'd like to remove the last line from a file. SolutionRead 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: $!"; DiscussionThis 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 Copyright © 2001 O'Reilly & Associates. All rights reserved. |
|