我有一个Perl脚本,它读取文件并搜索3个可能的字符串中的1个。
当它找到一个具有匹配字符串的行时,它会拆分空格中的行,选择结果数组中的一个元素,然后将该行与+一起重新连接,并将该行添加到散列中。
数据结构如下:
问题是正在将额外条目添加到具有无效密钥的哈希中。我删除了\r
的输入,并在将捕获的行添加到哈希之前将其写入文件。我无法弄清楚为什么会这样。
以下是代码:
sub ProcessInput() {
my $word;
foreach $word (@wantLines) {
if ($DEBUG) { print( $word, ":\t", $line, "\n" ); }
if ( $line =~ /$word/ ) {
if ( $word eq "C3_TIMEOUT_FRAME"
|| $word eq "RX_WT_AVG_B2B_ZERO"
|| $word eq "TX_WT_AVG_B2B_ZERO" )
{
if ($DEBUG) { print $word, "\n"; }
# store the counter in the hash
# the key is the entire line where spaces are replaced with '*'
# this is the only way to guarantee a unique key
print "Captured Line is $line\n";
my @values = split( " ", $line );
my $key = join( '*', @values );
my $epoch = parsedate( $values[3] ); #, GMT=>1);
open( FILE, ">$outfile" ) || die "Can't open file ($!)\n";
# unless (exists $hash{$epoch}->{$key})
unless ( exists $hash{$key} ) {
# print "Added key $key to the hash\n";
$hash{$epoch}->{$key} = $line;
# add the entry to the hash, but only if it doesn't exist already
# the value is the date for the log entry
# unless (exists $hash{$key})
$hash{$key} = $values[3];
} #unless
} #if $word
} #if $DEBUG
} #foreach
以下是一些输入。我加星标的行是无效散列条目之前的最后一行,但是在完整输出中还有更多。
fc1/11 |AK_FCP_CNTR_RX_WT_AVG_B2B_ZERO |199 |06/16/13 21:34:58
fc1/9 |AK_FCP_CNTR_RX_WT_AVG_B2B_ZERO |802 |06/16/13 21:16:52
**fc1/15 |AK_FCP_CNTR_RX_WT_AVG_B2B_ZERO |1588 |06/16/13 20:32:49**
fc1/15 |AK_FCP_CNTR_RX_WT_AVG_B2B_ZERO |1587 |06/16/13 17:28:10
fc1/15 |AK_FCP_CNTR_RX_WT_AVG_B2B_ZERO |1586 |06/16/13 16:29:41
fc1/11 |AK_FCP_CNTR_RX_WT_AVG_B2B_ZERO |198 |06/16/13 13:17:30
fc1/37 |AK_FCP_CNTR_RX_WT_AVG_B2B_ZERO |1025 |06/16/13 11:41:20
这是哈希,包括无效条目 - 无效条目是最后一个条目。
fc1/15*AK_FCP_CNTR_RX_WT_AVG_B2B_ZERO*1600*06/22/13*06:50:25 => 06/22/13
fc1/5*AK_FCP_CNTR_RX_WT_AVG_B2B_ZERO*125*06/17/13*07:39:40 => 06/17/13
fc1/9*AK_FCP_CNTR_RX_WT_AVG_B2B_ZERO*832*06/26/13*00:02:09 => 06/26/13
fc1/11*AK_FCP_CNTR_RX_WT_AVG_B2B_ZERO*209*06/21/13*09:26:09 => 06/21/13
fc1/15*AK_FCP_CNTR_RX_WT_AVG_B2B_ZERO*1588*06/16/13*20:32:49 => 06/16/13
1370923200 => HASH(0x97d5a0)
答案 0 :(得分:2)
首先,您的条目无效,它是哈希中的hashref,您使用$ hash {$ epoch} - > {$ key}插入它。 也许你想为此使用另一个哈希而不是$ hash?
然后,您应该清理间距字符以确保安全:
...
print "Captured Line is $line\n";
$line =~ s/\s+/ /g;
$line =~ s/^ | $//g;
my @values = split(" ", $line);
...
或者您也可以这样做:
...
print "Captured Line is $line\n";
$line =~ s/^\s+//;
my @values = split(/\s+/, $line);
...
另外,不要忘记关闭文件。