display | more...
Perl offers a simple way to interface with the Microsoft system via OLE.

While some may have difficulty with Perl as a language, citing confusing syntax and lack of enforcement of good programming practices, it makes the automation of operating system and application API's pretty easy and the use of the -w switch and 'use strict' pragma helps with the production of good code.

The following is a case in point:
I had a requirement to strip plain text from Microsoft Word documents.... Now this could be achieved by parsing an ASCII representation of the document and attempting to strip the text from the source, but a far easier way is to use Perl to open a Microsoft Word OLE object and load the file, saving it as text using Word itself. This was achieved in a few lines of Perl as below:

#!perl -w

# test script to translate an MS Word doc to plain text - uses the Word COM
# object and saves the new text file as .txt

use strict;
# import OLE
use Win32::OLE qw(in with);
use Win32::OLE::Const;
use Win32::OLE::Const 'Microsoft Word';
$Win32::OLE::Warn = 3;   # report OLE runtime errors

# specify variables
my $filename = 'c:\\test.doc';
my $savename = "$filename".".txt";

# instantiate Word - use the Word application if it's open, otherwise open new
print "Starting word\n";
my $Word = Win32::OLE->GetActiveObject('Word.Application')
    or Win32::OLE->new('Word.Application', 'Quit');
$Word->{Visible}= 0; # we don't need to see Word in an active window

# open the specified Word doc
print "Opening $filename\n";
$Word->Documents->Open( $filename )
	or die("Unable to open document ", Win32::OLE->LastError());

# save the file as a text file
print "Saving $filename "."as $savename\n";
$Word->ActiveDocument->SaveAs({
	FileName	=>	$savename,
	FileFormat	=>	wdFormatDOSTextLineBreaks});

# close document and Word instance
print "Closing document and Word\n";
$Word->ActiveDocument->Close();
$Word->Quit;

Footnote
I make no claim as to the elegance of the above code :)

Similar interaction is eminently feasible for all other Microsft operating systems and applications and is a good way to learn some of the basics of Perl.

This is of course possible in several other languages (Python being a good example), I just like Perl.

Log in or register to write something here or to contact authors.