1

我正在尝试在 Perl 中编写日志解析器。我想输出所有用户打印页数的列表。

日志导出为制表符分隔的文本文件。有几列信息,但所有重要的信息都在最后一列。重要的部分如下所示:

Document 34, Microsoft Word - Q5_Springc_2013 owned by USERNAME on COMPUTERHOSTNAME was printed on PRINTER through port PORT. Size in bytes: 42096. Pages printed: 4. No user action is required.

#!/usr/bin/perl
use warnings;
#use strict;

print "Export the \"Printed to...\" logs from Event Viewer for the desired printer as a .txt and place it in the same directory as this script!\n";
print "Enter the text file name: ";
my $infile = <STDIN>;

if ($infile eq "\n"){
    print "No filename entered! Exiting!";
    exit 0;
}
chomp $infile;

print "Reading from file $infile\n";
open INFILE, "<$infile" or die "File does not exist!";

my %report;
while(<INFILE>){

if (/ by (\S+) on .* printed: (\d+)/s) {
    $report{$1} += $2;
}

}

print "$_ $report{$_}\n" for (keys %report);
close INFILE or die $!;

我试图从用户名数组中提取唯一的名称并计算打印,但我没有找到比这更多的父亲。如果键存在但没有任何运气,我尝试改用哈希并通过将下一个值添加到旧值来使用键/值方案。谁能帮我弄清楚从这里去哪里?

我忘了提,我要的输出是这样的:

USER  45  
USER2 12  
USER3 120  
4

1 回答 1

1

以下是统计每个用户总和的快速方法:

my %hash;
while (<>) {
    if (/ by (\S+) on .* printed: (\d+)/s) {
        $hash{$1} += $2;
    }
}

哈希值是唯一的keys,因此它将是一个用户列表。

在相关说明中:

  • 如果您正在打开一个文件,是否将当前目录名添加到文件名前并不重要。Perl 明白,如果要打开file.txt,它首先会在当前目录中查找。
  • $i = $i + 1也称为$i += 1, 或$i++
  • 使用词法文件句柄和三个参数 open:open my $fh, "<", $file or die $!
  • 假设您提供文件名作为参数,您的整个程序可以用我的 6 行代码替换。
于 2013-06-26T01:46:18.213 回答