【发布时间】:2020-08-24 19:41:49
【问题描述】:
我正在读取输入文件并将数据存储在哈希中。稍后我想将哈希内容打印到 csv 文件。
这是脚本:
#!/usr/bin/perl
use strict;
use warnings;
use Data::Dumper;
my %hash;
while(<DATA>){
chomp;
my ($e_id, $start, $end, $priority, $node);
next unless /\S/;
my ($key, $val) = split /\s*:\s*/;
if($key =~ /eventId/) { $e_id = $val; }
if($key =~ /startTime/){ $start = $val; }
if($key =~ /endTime/) { $end = $val; }
if($key =~ /Node/) { $node = $val; }
if($key =~ /Priority/) { $priority = $val; }
$hash{$e_id}{'node'} = $node;
$hash{$e_id}{'start'} = $start;
$hash{$e_id}{'end'} = $end;
$hash{$e_id}{'priority'} = $priority;
}
print Dumper(\%hash);
__DATA__
Priority : High
Node : Node1
startTime : 2020-08-18T03:40:00
endTime : 2020-08-18T03:45:00
eventId : 150
Text : This is for Node1 text
eventPlace : Router1
Priority : Medium
Node : Node2
startTime : 2020-08-19T00:00:10
endTime : 2020-08-19T00:00:40
eventId : 170
Text : This is for Node2 text
eventPlace : Router2
但是这里hash 没有按预期打印。 Hash 的主键应该是$e_id,辅助键应该是node,start,end,priority,并且从文件中获取它们各自的eventId的值。
我想像这样打印哈希:
$VAR1 = { '150' => {
'end' => 2020-08-18T03:45:00,
'priority' => High,
'start' => 2020-08-18T03:45:00,
'node' => Node1
},
'170' => {
'end' => 2020-08-19T00:00:40,
'priority' => Medium,
'start' => 2020-08-19T00:00:10,
'node' => Node2
}
};
我该怎么做。还请建议一种合适的方法来读取文件(我怀疑我做错了什么)。因为它会引发警告 - Use of uninitialized value $e_id in hash element at a.pl line .., <DATA> line ..
【问题讨论】: