woodstea has asked for the wisdom of the Perl Monks concerning the following question:
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
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: tail -1 emulation efficiency
by BrowserUk (Patriarch) on May 06, 2004 at 03:52 UTC | |
|
Re: tail -1 emulation efficiency
by coec (Chaplain) on May 06, 2004 at 02:33 UTC | |
by woodstea (Sexton) on May 06, 2004 at 02:50 UTC | |
by matija (Priest) on May 06, 2004 at 04:43 UTC | |
|
Re: tail -1 emulation efficiency
by gsiems (Deacon) on May 06, 2004 at 02:58 UTC | |
|
Re: tail -1 emulation efficiency
by eserte (Deacon) on May 06, 2004 at 09:25 UTC | |
|
Re: tail -1 emulation efficiency (use File::ReadBackwards)
by grinder (Bishop) on May 06, 2004 at 10:17 UTC | |
|
Re: tail -1 emulation efficiency
by zentara (Cardinal) on May 06, 2004 at 16:13 UTC | |
|
Re: tail -1 emulation efficiency
by blue_cowdawg (Monsignor) on May 06, 2004 at 02:48 UTC | |
by woodstea (Sexton) on May 06, 2004 at 03:11 UTC |