最近在做一个实时数据的工作,需要读取不断更新的文件,类似shell中tail的功能,使用了perl的File::Tail模块,简要代码如下
use File::Tail;
my $file=File::Tail->new(name=>&new_file($first_file_date),interval=>1,maxinterval=>10,tail=>-1,reset_tail=>-1,name_changes=>\&new_file,debug=>1);
while (defined(my $line=$file->read)) {
...
}
sub get_cur_date{
my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst)=localtime();
$year+=1900;
$mon++;
if($mon<10){$mon="0".$mon;}
if($mday<10){$mday="0".$mday;}
$year.$mon.$mday;
}
sub new_file{
my $file_date=$_[0]||&get_cur_date();
return "/logdir/logfile".$file_date.".log";
};
参数说明:设置tail参数为正数,将从头读取文件
设置name_change为一个函数引用,即读取当前文件的下一个文件,本例中的文件是以天记的
设置interval,即程序启动后距离第一次读取文件的时间间隔
设置maxinterval,即当文件没有更新时,程序的sleep时间
参考:http://search.cpan.org/~mgrabnar/File-Tail-0.99.3/Tail.pm