pure perl tail
时间:2009-04-11 来源:socyno
pure perl tail
by zentara on Sep 06, 2002 at 20:29 UTC
http://www.perlmonks.org/index.pl?node_id=195768
Description: | Oh well, this question keeps popping up every few months. How do I tail a large file with perl? Here is my crack at it, it uses seek from the end of the file. Linux only for now. Bill Gates dosn't seem to care about linux compatibility, so why should I care about windows compatibility? |
#!/usr/bin/perl -w # Simple program to read the last n line(s) of a file. # Reads from the end of the file for effeciency # "\n" linux only, # usage tailz filename numberoflines use strict; my $filename = shift or die "Usage: $0 file numlines\n"; my $numlines = shift; my $byte; # Open the file in read mode open FILE, "<$filename" or die "Couldn't open $filename: $!"; # Rewind from the end of the file until count of eol 's seek FILE,-1, 2; #get past last eol my $count=0; while (1){ seek FILE,-1,1; read FILE,$byte,1; # ASCII code 10 is newline char if(ord($byte) == 10 ){$count++;if($count == $numlines){last}} seek FILE,-1,1; if (tell FILE == 0){last} } $/=undef; my $tail = <FILE>; print "$tail\n"; |
相关阅读 更多 +