Earlier today I was searching the site for a way to emulate the UN*X tail command in Perl, specifically, tailing just the last line of a huge log file. I spent some time reading Simulating UNIX's "tail" in core Perl, and after some thought, I realize that for my specific application (and given who else might be maintaining the program now and in the future), that simply running the system tail command is probably the best way to go. Easy, fast - it's fine really.
I can't help wondering, though - just for educational reasons - what the most efficient way to get that last line is. I've got to think that while'ing through every line can't be right, especially for very large files. I'd think using seek might be better, so I put together a little program to seek backwards from the next-to-last character of the file to the first newline encountered, and print everything following. Here's what I've got:
use strict; open(FILE, $ARGV[0]) or die; my($i,$char); for ($i=-2;;$i--) { seek(FILE,$i,2) or exit; read(FILE,$char,1); $char eq "\n" and last; } while (<FILE>) { print; } close FILE;
This is my first encounter with seek (and my first post here), so I'm looking for feedback. Does this make sense? More efficient ways to do this? Pitfalls?
Thanks, Rob
In reply to tail -1 emulation efficiency by woodstea
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |