Perl根据条件解析文件

问题描述:

我有一个非常大的日志文件,它会定期更新。这是因为如下:Perl根据条件解析文件

commands: (List of files to be copied) 
Exit time: Fri May 10 05:33:00 2013 
Exit status: 2 

commands: (List of files to be copied) 
Exit Time: Fri May 20 05:34:00 2013 
Exit status: 2 

commands: (List of files to be copied) 
Exit Time: Fri May 30 05:50:00 2013 
Exit Status: 1 

我有以下根据退出状态,其产生的哈希码

while ($line = <FH>) { 
     if ($line =~ /Exit time/) { 
     ($exittime, $exittimeval) = split(': ',$line); 
     $stat{$qbsid} = { 
      time  => $exittimeval 
      }; 
} 

我现在需要基于本地时间使得脚本不比较日志创建时间戳文件的时间戳后(本地时间)。我的代码进行比较的时候如下

$date1 = "$hr1:$min1:$sec1, $moy1/$dt1/$yr1"; 
$date2 = "$hr2:$min2:$sec2, $moy2/$dt2/$yr2"; 
sub to_comparable { 
    my ($date) = @_; 
    my ($H,$M,$S,$d,$m,$Y) = $date =~ m{^(\d+):(\d+):(\d+), (\d+)/(\d+)/(\d+)\z} 
     or die; 
    return "$Y$m$d$H$M$S"; 
} 

if (to_comparable($date2) > to_comparable($date1)) { 
print "right\n"; 
} else { 
     print "wrong \n"; 
} 

这里$ HR1,$ MIN1,$秒-1,$ moy1,$ DT1及$ YR1均为当地时间变量而HR2,$ MIN2,$秒2,$ moy2,$ dt2和$ yr2是从散列获得的值。

最好在首次运行时比较整个文件并创建一个时间戳。之后,上述想法开始。

如果有任何问题,请纠正我。谢谢。

您可能要考虑使用Time::Piece,它首次在perl v5.9.5中发布。

#!/usr/bin/perl 
use strict; 
use warnings; 
use Time::Piece; 

{ 
    my $end_date = '2013-05-30'; 

    local $/ = ''; 
    while (<DATA>) { 
     if (/^Exit Time: (.+)/m) { 
      my $date = Time::Piece->strptime($1, "%c"); 
      print $date->ymd, "\n" if $date->ymd lt $end_date; 
     } 
    } 
} 

__DATA__ 
commands: (List of files to be copied) 
Exit Time: Fri May 10 05:33:00 2013 
Exit status: 2 

commands: (List of files to be copied) 
Exit Time: Fri May 20 05:34:00 2013 
Exit status: 2 

commands: (List of files to be copied) 
Exit Time: Fri May 30 05:50:00 2013 
Exit Status: 1 

输出:

2013-05-10 
2013-05-20 
+0

任何替代时间::件module..If我可以像年,月,日,小时,分钟,秒等正常比较..只是一个建议..谢谢 – deep

+0

@deep它可用于Perl 10或更新版本。你为什么不想用它?是的,如果需要,你可以手工编写代码。 –

您将形成一个20位数的数字(假设年份是4位数,其余的总是2位数字)。这是一个很大的数字,但在我的64位UNIX操作系统上似乎很好;我不知道你的。无论如何,使用固定长度的字符串,如果数字很大是个问题,则可以进行字符串比较(“ge”而不是“>”)。

如果任何输入(例如$ moy1)可能是单个数字,那么从10月1日(2013101)开始到9月30日(2013930)之前,您的比较函数将不起作用。你可能需要的位数固定数量的使用:

my ($H,$M,$S,$d,$m,$Y) = $date =~ m{^(\d\d):(\d\d):(\d\d), (\d\d)/(\d\d)/(\d\d\d\d)\z} 
     or die; 

我敢肯定$ qbsid是如何设置的(退出状态或别的东西),但由于你的代码没有完成我假设你有别的东西去做。

我也不确定您的原始时间字符串(例如“Fri May 30 05:50:00 2013”​​)转换为“$ hr1:$ min1:$ sec1,$ moy1/$ dt1/$ yr1“格式,但我假设你在其他地方也这样做。

+0

@kjpres它是16位number..So,它好工作为system..Thanks – deep