我正在尝试编写一个Perl脚本来解析日志,其中每行第二个值是日期。该脚本包含三个参数:输入日志文件,开始时间和结束时间。开始和结束时间用于解析每行之间的某个值,该值介于这两次之间。但为了正确运行这个,我将开始和结束时间转换为纪元时间。我遇到的问题是将循环'i'值转换回正常时间以与日志文件进行比较。运行localtime($i)
后,我打印了值,只看到打印的参考值而不是实际值。
这是我到目前为止的脚本(这是一项正在进行的工作):
#!/usr/bin/perl
use strict;
use warnings;
use Time::Local;
use Time::localtime;
use File::stat;
my $sec = 0;
my $min = 0;
my $hour = 0;
my $mday = 0;
my $mon = 0;
my $year = 0;
my $wday = 0;
my $yday = 0;
my $isdst = 0;
##########################
# Get the engine log date
##########################
my $date = `grep -m 1 'Metric' "$ARGV[0]" | awk '{print \$2}'`;
($year,$mon,$mday) = split('-', $date);
$mon--;
#########################################
# Calculate the start and end epoch time
#########################################
($hour,$min,$sec) = split(':', $ARGV[1]);
my $startTime = timelocal($sec,$min,$hour,$mday,$mon,$year);
($hour,$min,$sec) = split(':', $ARGV[2]);
my $endTime = timelocal($sec,$min,$hour,$mday,$mon,$year);
my $theTime = 0;
for (my $i = $startTime; $i <= $endTime + 29; $i++) {
#print "$startTime $i \n";
$theTime = localtime($i);
#my $DBInstance0 = `grep "$hour:$min:$sec" "$ARGV[0]"`;# | grep 'DBInstance-0' | awk '{print \$9}'`;
#print "$DBInstance0\n";
print "$theTime\n";
}
print "$startTime $endTime \n";
输出如下:
Time::tm=ARRAY(0x8cbbd40)
Time::tm=ARRAY(0x8cbc1a0)
Time::tm=ARRAY(0x8cbbe80)
Time::tm=ARRAY(0x8cbc190)
Time::tm=ARRAY(0x8bbb170)
Time::tm=ARRAY(0x8cbc180)
Time::tm=ARRAY(0x8cbbf30)
Time::tm=ARRAY(0x8cbc170)
Time::tm=ARRAY(0x8cbc210)
Time::tm=ARRAY(0x8cbc160)
1275760356 1275760773
我只能访问核心Perl模块,无法安装任何其他模块。
答案 0 :(得分:3)
您可以使用ctime
,具体取决于您对“正常时间”的定义:
示例代码:
use Time::Local;
use Time::localtime;
my $time=timelocal(1,2,3,24,6,2010);
print "$time\n";
$theTime = ctime($time);
print "$theTime\n";
结果:
1279954921
Sat Jul 24 03:02:01 2010
此外,您不需要使用Time :: Localtime(which is why you get Time::tm而不是Perl的内部localtime
中的标准数组/字符串):
use Time::Local;
my $time=timelocal(1,2,3,24,6,2010);
print "$time\n";
$theTime = localtime($time);
print "$theTime\n";
1279954921
Sat Jul 24 03:02:01 2010
答案 1 :(得分:2)
不要忘记从年份中减去1900!
请记住,在标量上下文中,localtime
和gmtime
会返回ctime
格式的字符串,因此您可以按照以下方式使用它。如果这不合适,您可能希望使用POSIX
模块中的strftime
。
#! /usr/bin/perl
use warnings;
use strict;
use Time::Local;
my $start = "01:02:03";
my $end = "01:02:05";
my $date = "2010-02-10";
my($year,$mon,$mday) = split /-/, $date;
$mon--;
$year -= 1900;
my($startTime,$endTime) =
map { my($hour,$min,$sec) = split /:/;
timelocal $sec,$min,$hour,$mday,$mon,$year }
$start, $end;
for (my $i = $startTime; $i <= $endTime + 29; $i++) {
print scalar localtime($i), "\n";
}
print "$startTime $endTime \n";
输出尾巴:
Wed Feb 10 01:02:26 2010 Wed Feb 10 01:02:27 2010 Wed Feb 10 01:02:28 2010 Wed Feb 10 01:02:29 2010 Wed Feb 10 01:02:30 2010 Wed Feb 10 01:02:31 2010 Wed Feb 10 01:02:32 2010 Wed Feb 10 01:02:33 2010 Wed Feb 10 01:02:34 2010 1265785323 1265785325