Aurelia Peters
Aurelia Peters

Reputation: 2209

Clean way to write OLE code in Perl?

I'm working with automating the creation of a Word document in Perl by means of Win32::OLE. My current code looks like this, and it's leaving instances of WINWORD.EXE in memory:

my $range = $select->Range;
my $table = $doc->Tables->Add( $range, scalar @rows, scalar @{ $rows[0] } );
for my $rownum ( 0 .. $#rows ) {
    for my $colnum ( 0 .. $#{ $rows[$rownum] } ) {
        my @cellpos = ( $rownum + 1, $colnum + 1 );
        my $data = $rows[$rownum][$colnum];
        $table->Cell(@cellpos)->Range->{'Text'} = $data;
        1;
    }
}

However, if I were to refactor my code per the Microsoft recommendation for Visual Studio .NET, it would look like this:

my $range = $select->Range;
my $tables = $doc->Tables;
my $table = $tables->Add( $range, scalar @rows, scalar @{ $rows[0] } );
for my $rownum ( 0 .. $#rows ) {
    for my $colnum ( 0 .. $#{ $rows[$rownum] } ) {
        my @cellpos = ( $rownum + 1, $colnum + 1 );
        my $data = $rows[$rownum][$colnum];
        my $cell = $table->Cell(@cellpos);
        my $cell_range = $cell->Range;
        $cell_range->{'Text'} = $data;
    }
} 

That code does the job, but it's awfully "noisy" to my mind. Is there a cleaner way to do this?

Upvotes: 1

Views: 195

Answers (1)

Borodin
Borodin

Reputation: 126722

It can be improved marginally. There is no need for the @cellpos and $data variables, and it is tidier to extract a reference to the current element of @rows for use within the inner loop.

my $range = $select->Range;
my $tables = $doc->Tables;
my $table = $tables->Add( $range, scalar @rows, scalar @{ $rows[0] } );
for my $rownum ( 0 .. $#rows ) {
    my $cols = $rows[$rownum];
    for my $colnum ( 0 .. $#$cols ) {
        my $cell = $table->Cell($rownum + 1, $colnum + 1);
        my $cell_range = $cell->Range;
        $cell_range->{Text} = $cols->[$colnum];
    }
} 

Upvotes: 1

Related Questions