in reply to Last N lines from file (tail)
Update: It does work when requesting more lines than the file contains, though I fixed it to work with various buffer sizes. I don't think a 20000% speed improvement (for tailing 400 10 byte lines) is 'too much' optimization :-) It does miscount if the last line does not have a line feed, though do you actually count that as a line or not? Besides, your's 'miscounts' in that situation also.sub lastn { my($file, $lines, $bufsiz)=@_; $bufsiz ||= 1024; # Changed FH to STDOUT to avoid warning my $fh = \do { local *STDOUT }; $lines++; if (! open($fh, $file) ) { print "Can't open $file: $!<P/>"; return; } binmode($fh); my $pos = sysseek($fh, 0, 2); # Seek to end my $nlcount=0; while($nlcount<=$lines) { $bufsiz = $pos if $bufsiz > $pos; $pos = sysseek($fh, -$bufsiz, 1); die "Bad seek: $!" unless defined $pos; my $bytes = sysread($fh, $_, $bufsiz, 0); die "Bad read: $!" unless defined $bytes; $nlcount += tr/\n//; $pos = sysseek($fh, -$bufsiz, 1); die "Bad seek: $!" unless defined $pos; last if $pos == 0; } seek($fh, sysseek($fh, 0, 1), 0) || warn; <$fh> for $lines..$nlcount; $fh; }
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Re: Last N lines from file (tail)
by clintp (Curate) on Dec 19, 2001 at 01:49 UTC | |
by SpongeBob (Novice) on Dec 22, 2001 at 02:02 UTC |