如何在Perl中优化以下代码?

时间:2019-03-05 09:46:55

标签: regex excel perl

如何在Perl中使用哈希和数组来优化以下Excel代码?是否有任何方法可以减少以下示例的代码行?

示例1:-

$style = $workbook->add_format();
$style->set_bold();
$style->set_bg_color('blue');
$style->set_align('center');
$style->set_border(1);
$style->set_border_color('black');

示例2:-

$worksheet->write_col("A2",$file1);
$worksheet->write_col("B2",$file2);
$worksheet->write_col("C2",$file3,$style);
$worksheet->write_col("D2",$file4,$style);

1 个答案:

答案 0 :(得分:2)

下面是一个示例,说明如何在for循环中将add_format()与哈希和write()一起使用:

use strict;
use warnings;
use Spreadsheet::WriteExcel;

my $workbook = Spreadsheet::WriteExcel->new('formats.xls');


my $worksheet = $workbook->add_worksheet('Introduction');

my %format = (bold => 0, bg_color => 'blue', align => 'center',
          border => 1, border_color => 'black');
my $style = $workbook->add_format(%format);
$worksheet->write(4, 0, 'This workbook demonstrates some of',  $style);
$worksheet->write(5, 0, 'the formatting options provided by',  $style);
$worksheet->write(6, 0, 'the Spreadsheet::WriteExcel module.', $style);

my ( $file1, $file2, $file3, $file4 ) = qw(file1 file2 file3 file4);
my %write_col = ( A2 => [$file1], B2 => [$file2],
                  C2 => [$file3, $style], D2 => [$file4, $style] );
$worksheet->write($_, @{$write_col{$_}}) for keys %write_col;

$workbook->close();