tags:

views:

59

answers:

1

I am actually trying to change the color index for the first word with braces in an array so they show up in the right color in Word 2003.

For example, if I have an array like this:

@array="
        (This) is (perl),
         perl is a great (language),
         we can do anything with perl,
         (perl) feels us great."

I need the colour of the first word that is inside the parentheses (), i.e. (This) and (perl) including () to be in red and rest of the contents in black. and print the entire contents of the array in MS Word 2003:

I'm using Win32::OLE and Windows XP. This array is just an example the contents of an array will change but first word with braces has to be printed in red.

+3  A: 
#!/usr/bin/perl

use strict; use warnings;
use Win32::OLE;
use Win32::OLE::Const 'Microsoft Word';
$Win32::OLE::Warn = 3;

my $word = get_app('Word.Application');
$word->{Visible} = 1;

my $doc = $word->Documents->Add;

while ( my $line = <DATA> ) {
    my @chunks = split /(\(\w+\))/, $line;
    my $seen;
    for my $chunk ( @chunks ) {
        my $sel = $word->Selection;
        my $font = $sel->Font;
        if ( $chunk =~ /^\(/ and not $seen) {
            $font->{ColorIndex} = wdRed;
            $seen = 1;
        }
        else {
            $font->{ColorIndex} = wdBlack;
        }
        $sel->TypeText($chunk);
    }
}

sub get_app {
    my ($class) = @_;
    my $app;
    eval {
        $app = Win32::OLE->GetActiveObject($class);
    };

    if ( my $ex = $@ ) {
        die $ex, "\n";
    }

    unless(defined $app) {
        $app = Win32::OLE->new($class, sub { $_[0]->Quit })
            or die "Oops, cannot start '$class': ",
                   Win32::OLE->LastError, "\n";
    }
    return $app;
}

__DATA__
(This) is (perl),
perl is a great (language),
we can do anything with perl,
(perl) feels us great.
Sinan Ünür