我有一个键和Values(array)的哈希。我想将它们转储到电子表格中,但是很难安排它们。
%hash key1-
> foo bar
key2-> john adam gill
key3->苹果香蕉芒果橙
代码:
use strict;
use warnings;
use Excel::Writer::XLSX;
my $pattern = "BEGIN_";
my $format;
my @keys = qw(key1 key2 key3);
foreach my $key(@keys){
open my $fh, "<","filename.txt" or die $!;
while ( <$fh> ) {
if (/$pattern/) {
push(@matching_lines, $_);
}
}
$hash{$key} = [@matching_lines] ;
for (@matching_lines) { $_ = undef } ; #Emptying the array contents,to reuse it for for all the other keys
}
my $workbook = Excel::Writer::XLSX->new( 'c:\TEMP\filename.xlsx' );
if (not defined $workbook)
{
die "Failed to create spreadsheet: $!";
}
my $worksheet = $workbook->add_worksheet();
# Add and define a format
$format = $workbook->add_format();
$format->set_bg_color( 'yellow' );
my $row = 1;
my $col = 0;
foreach my $k (keys %hash)
{
$worksheet->write($row, $col, $k, $format); # title
$worksheet->write_col($row+1, $col, $hash{$k}); #value
$col++;
}
$workbook->close() or die "Error closing file: $!";
电流输出
您没有正确清空@matching_lines
数组。这行:
for (@matching_lines) { $_ = undef }
将数组值设置为undef
,但不删除它们。
例如,如果@matching_lines
是('foo', 'bar')
,现在变为(undef, undef)
。以后添加baz
和添加时qux
,它将变为(undef, undef, 'baz', 'qux')
。undef
将它们添加到工作表时,这些将成为空白单元格。
要正确清空数组,请使用:
@matching_lines = ();
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句