解析速度慢并发送到数据库



我在perl中有这段代码,我想发送到一个数据库中。

我的代码 :

my $dir = '/mnt/Logs/';
foreach my $fp (glob("$dir/SESSIONS*")) {
  printf "%sn", $fp;
  open my $fh, "<", $fp or die "can't read open '$fp': $OS_ERROR"
while ($fh) {
    @line = split(' ',$_);      
    print "$line[0] $line[1] $line[2] $line[3] $line[4] $line[5]n";
}

原木:

           SID OSUSER                    TERMINAL        PROGRAM                    
    ---------- ------------------------- --------------- -------------------------  
             1 titi                    toto     tata          
             2 gigi                    gogo     gaga          
             4 fifi                    fofo     fafa 
3 rows selected.

我的问题是如何做到这一点:

SID OSUSER                  TERMINAL PROGRAM  rows selected         
  1 titi                    toto     tata     3    
  2 gigi                    gogo     gaga     3   
  4 fifi                    fofo     fafa     3

在处理完所有行之前,您不知道行数。因此,将输出保存在缓冲区中,并在文件处理结束时打印它:

    #!/usr/bin/perl
    use warnings;
    use strict;
    use feature qw{ say };
    open my $fh, '<', 'log' or die $!;
    my @buffer;
    while (<$fh>) {
        next if $. < 3;
        if (/^([0-9]+) rows selected.$/) {
            die "Wrong number of rows reported: $1, seen ", scalar @buffer
                if $1 != @buffer;
        } else {
            push @buffer, [ split ' ' ];
        }
    }
    for (@buffer) {
        say join "t", @$_, scalar @buffer;
    }

或处理文件两次。在第一次运行中,只需数行,在第二次运行中,逐个打印它们,并附加计数:

open my $fh, '<', 'log' or die $!;
1 while <$fh>;
my $size = $. - 3;
seek $fh, $. = 0, 0;
while (<$fh>) {
    next if $. < 3;
    if (/^([0-9]+) rows selected.$/) {
        die "Wrong number of rows reported: $1, seen ", $size
            if $1 != $size;
    } else {
        say join "t", split(' '), $size;
    }
}

最新更新