我正在使用Text::CSV::Slurp
从哈希数组中创建CSV文件。除了一些标题缺失外,它的效果很好。
hash1
header1 header2
1 2
hash2
header1 header2 header3
11 22 33
我希望最终输出为CSV文件:
header1 header2 header3
1 2
11 22 33
不是啜食输出
header1 header2
1 2
11 22
有什么建议吗?
代码:
sub entry_capture_csv {
my ($stores_folder, $cmdstr, $header_field, $entrycmdstr, $entryfilename) = @_;
print "\t\tOSSI-" . $cmdstr . " for " . $entryfilename . " entry detail\n";
$node->pbx_command($cmdstr);
if ( $node->last_command_succeeded() ) {
my @ossi_output = $node->get_ossi_objects();
my $i = 0;
my @ext_array;
foreach my $hash_ref(@ossi_output) {
$i++;
#print "output result $i\n";
for my $field ( sort keys %$hash_ref ) {
my $value = $hash_ref->{$field};
#print "\t$field => $value\n";
}
my $entryNumber = trim($hash_ref->{$header_field});
unless( defined $entryNumber ) { $entryNumber = '' };
if ($entryNumber eq "") {
#empty string
} else {
push(@ext_array, $entryNumber);
}
}
# Issue = failed sometimes there is extra header
#
my @result_array;
foreach (@ext_array) {
my $entrycmd = $entrycmdstr . " " . $_;
$node->pbx_command($entrycmd);
if ( $node->last_command_succeeded() ) {
print "\t\t\t" . $entrycmd . "\n";
my @ossi_output = $node->get_ossi_objects();
push(@result_array, @ossi_output);
#my $csv = Text::CSV::Slurp->create( input => \@ossi_output );
#open (OUTFILE, ">$stores_folder/$store-" . $entryfilename . "-" . "$_" . ".csv") || die "Can't open output file.\n";
#print OUTFILE $csv;
#close(OUTFILE);
} else {
print "Failed\t\t\t" . $entrycmd . "\n";
}
}
my $csv = Text::CSV::Slurp->create( input => \@result_array );
open (OUTFILE, ">$stores_folder/$store-" . $entryfilename . ".csv") || die "Can't open output file.\n";
print OUTFILE $csv;
close(OUTFILE);
}
}
答案 0 :(得分:0)
Text::CSV::Slurp->create
构造函数方法采用field_order
选项,该选项定义要使用的哈希元素的键及其在CSV记录中的顺序。
看看这段代码,我认为这是不言自明的。
use strict;
use warnings;
use Text::CSV::Slurp;
my @data = (
{
header1 => 1,
header2 => 2,
},
{
header1 => 11,
header2 => 22,
header3 => 33,
},
);
my $csv = Text::CSV::Slurp->create(
input => \@data,
field_order => [qw/ header1 header2 header3 /]);
print $csv;
<强>输出强>
header1,header2,header3
1,2,
11,22,33
<强>更新强>
要自动从数据中获取标题列表,您可以编写类似这样的内容。输出与前一个程序的输出相同。
请注意,无法知道如何最好地对标题列表进行排序,因此我使用了一个简单的词法排序。它通过这些琐碎的数据产生了预期的效果。
use strict;
use warnings;
use Text::CSV::Slurp;
my @data = (
{
header1 => 1,
header2 => 2,
},
{
header1 => 11,
header2 => 22,
header3 => 33,
},
);
my @headers = do {
my %headers;
$headers{$_}++ for map { keys %$_ } @data;
sort keys %headers;
};
my $csv = Text::CSV::Slurp->create(
input => \@data,
field_order => \@headers);
print $csv;