2010-03-17 63 views
-3

我其实是想改变为用大括号的第一个字的颜色索引的数组,使他们在Word 2003中如何使用Win32:OLE更改msword字符串中单词的颜色索引?

例如合适的颜色显示出来,如果我有一个这样的数组:

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

我需要的第一个词就是括号内()的颜色,即(This)(perl)包括()是在红色和黑色的内容休息。并在MS Word 2003中打印整个数组的内容:

我使用的是Win32::OLE和Windows XP。这个数组只是一个例子,数组的内容将会改变,但带大括号的第一个单词必须以红色打印。

+0

“感觉我们很棒”听起来性感,否则就没有意义。即使这是一个延伸。我知道你不是英语母语的人,所以不要这样说,除非你想让人们嘲笑你。 “(perl)让我们感觉很棒”,或者“(perl)让我感觉棒极了”或“(perl)感觉棒极了”是可以接受的。 – 2010-03-17 13:49:56

+0

你知道,思南,只要你继续以优异的答案奖励他,他就不会改变他的行为。 :) – 2010-03-17 14:46:25

+0

@brian真的,非常真实。但是,请注意,我的代码还特意为“(语言)”添加了红色。此外,我尝试遵循网站关于问题和答案的原则,而不是个人海报。所以,我实际上选择等待大约10个小时才回答他的**紧急问题。 – 2010-03-17 16:36:41

回答

2
#!/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 = [email protected]) { 
     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.