【发布时间】:2016-05-11 06:00:59
【问题描述】:
我正在尝试打开一个日志文件,根据关键字列表搜索它,打印包含该关键字的每一行,然后将结果文件压缩为 .gz。
我想出了下面的代码,它开始运行时没有编译错误。它写入结果文件,但是当我运行脚本时,它永远不会完成,也永远找不到任何结果。有什么帮助吗?
#!/usr/bin/perl
use IO::Uncompress::Gunzip qw($GunzipError);
use IO::Compress::Gzip qw(gzip $GzipError) ;
use diagnostics;
use strict;
use warnings;
my %LOGLINES = ();
my %count = ();
open(FILE, "</data/bro/scripts/Keywords.txt");
my %keywords = map { chomp $_; $_, 1 } <FILE>;
close(FILE);
my $logfile = IO::Uncompress::Gunzip->new( "/data/bro/logs/2016-05-05/http.00:00:00-06:00:00.log.gz" )
or die "IO::Uncompress::Gunzip failed: $GunzipError\n";
open(FILE, "+>Results.txt");
my @results = <FILE>;
foreach my $line ($logfile) {
while (<>) {
my @F=split("\t");
next unless ($F[2] =~ /^(199|168|151|162|166|150)/);
$count{ $F[2] }++;
if ($count{ $F[2] } == 10) {
print @{ $LOGLINES{$F[2]} }; # print all the log lines we've seen so far
print $_; # print the current line
} elsif ($count{ $F[2] } > 10) {
print $_; # print the current line
} else {
push @{ $LOGLINES{$F[2]} }, $_; # store the log line for later use
}
my $flag_found = grep {exists $keywords{$_} } split /\s+/, $line;
print $line if $flag_found;
}
}
IO::Compress::Gzip("results.gz")
or die "IO::Compress::Gunzip failed: $GzipError\n";
close(FILE);
【问题讨论】:
-
一般
while (<>)行涉及键盘输入。也许这就是你的脚本“永远不会完成”的原因。 -
@red0ct 是正确的。
while循环的目的是什么?它要你输入东西。您已经使用foreach循环了$logfile的行(虽然只有一次,因为您没有在 ::Gunzip 对象上调用任何东西)。 -
while 循环会一直搜索日志文件的每一行,直到到达末尾。我是不是走错路了?
-
我认为
while (<$logfile>)会帮助你。因为 AFAIK 对象,由IO::Uncompress::Gunzip->new返回可以像普通文件句柄一样处理.. -
另外,为什么要以读写模式打开Results.txt?你从不使用
@results,你也不写信给FILE。你有strict和warnings,你的代码看起来很不错。还可以使用三参数开放来使其更好。 :)