这是我的代码:
my %hash = (
'2564' => {
'st_responsible' => 'mname1',
'critical' => '',
'last_modified_by' => 'teamname1',
'transstatus' => '',
'rt_res' => 'pname1'
},
'2487' => {
'st_responsible' => 'mname2',
'critical' => '',
'last_modified_by' => 'teamname2',
'transstatus' => '',
'rt_res' => ''
}
);
print "xnum,st_responsible,critical,last_modified_by,transstatus,rt_res\n";
foreach my $x_number (sort keys %hash)
{
print "$x_number";
foreach my $element (keys %{$hash{$x_number}})
{
print ",$hash{$x_number}{$element}";
}
print "\n";
}
预期输出
xnum,st_responsible,critical,last_modified_by,transstatus,rt_res
2487,mname2,,teamname2,,
2564,mname1,,teamname1,,pname1
实际输出
xnum,st_responsible,critical,last_modified_by,transstatus,rt_res
2487,mname2,,,teamname2,
2564,mname1,,,teamname1,pname1
请帮助我了解如何准确保留此数据结构的顺序,然后将其写入 CSV
文件。
最佳答案
我建议为此,您最好使用 slice
来执行此操作。 ,这是一种按特定顺序从哈希中提取值列表的方法?
#configure field order
my @order = qw ( st_responsible critical last_modified_by transstatus rt_res );
#print header row
print join (",", "xnum", @order ),"\n";
#iterate the rows
foreach my $key ( sort keys %hash ) {
#extract hash slice and join it with commas
print join ( ",", $key, @{$hash{$key}}{@order} ),"\n";
}
这给出:
xnum,st_responsible,critical,last_modified_by,transstatus,rt_res
2487,mname2,,teamname2,,
2564,mname1,,teamname1,,pname1
您可以考虑 Text::CSV
- 但我建议在这种情况下它有点矫枉过正,最好在您需要担心引号和带引号的字段分隔符时使用。 (而你没有)。
如果您不仅需要处理空键,还需要处理丢失的键,您可以使用 map
:
my @order = qw ( st_responsible critical last_modified_by
transstatus missing rt_res extra_field_here );
print join (",", "xnum", @order ),"\n";
foreach my $key ( sort keys %hash ) {
print join ( ",", $key, map { $_ // '' } @{$hash{$key}}{@order} ),"\n";
}
(否则您将收到有关 undef 值的警告)。
关于perl - 维护哈希值的哈希值中的顺序,并输出为 .csv,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35078803/