Perl如何提取日志时间戳列表中每个日期的最早与最晚时间
Perl脚本修改方案
现有脚本问题
- 哈希存储结构不合理,仅支持存储单个时间值,无法同时记录最早、最晚两个时间
- 代码中
next关键字后的逻辑永远无法执行,原有的时间比较逻辑完全未生效 - 未正确定义时间匹配格式,Time::Piece的格式转换逻辑存在错误
修正后完整脚本
use strict; use warnings; use Time::Piece; # 定义时间戳匹配格式,对应 年-月份缩写-日 时:分:秒 my $dt_format = "%Y-%b-%d %H:%M:%S"; my %date_records; # 读取输入文件,替换为你的实际日志文件路径 open my $IN, '<', 'log_file_path' or die $!; while (<$IN>) { # 去除前后空白符和换行 s/^\s+|\s+$//g; next if !$_; # 跳过空行 # 整行转成Time::Piece对象方便比较 my $current_dt = eval { Time::Piece->strptime($_, $dt_format) }; next if $@; # 跳过格式不匹配的行 # 提取日期部分作为哈希key my $date_key = $current_dt->strftime("%Y-%b-%d"); # 首次出现该日期时直接初始化最早最晚时间 if (!exists $date_records{$date_key}) { $date_records{$date_key} = { min => $current_dt, max => $current_dt }; next; } # 非首次出现则和已有值比较更新 if ($current_dt < $date_records{$date_key}{min}) { $date_records{$date_key}{min} = $current_dt; } if ($current_dt > $date_records{$date_key}{max}) { $date_records{$date_key}{max} = $current_dt; } } close $IN; # 按日期顺序输出结果 foreach my $date (sort keys %date_records) { print "begin : " . $date_records{$date}{min}->strftime($dt_format) . "\n"; print "end : " . $date_records{$date}{max}->strftime($dt_format) . "\n"; }
修改说明
- 调整哈希存储结构:每个日期key对应存储
min(最早时间)和max(最晚时间)两个Time::Piece对象,无需重复做字符串转时间的操作 - 修正逻辑错误:移除原脚本中无效的
next后代码,每次读取到合法时间戳都会和当前日期的最早、最晚时间做比较,更新对应值 - 增加容错处理:跳过空行和格式不匹配的行,避免脚本运行报错
- 输出完全匹配要求的格式
内容的提问来源于stack exchange,提问作者mrJa
相关产品推荐
相关产品推荐

