home *** CD-ROM | disk | FTP | other *** search
/ Netrunner 2004 October / NETRUNNER0410.ISO / regular / ActivePerl-5.8.4.810-MSWin32-x86.msi / _c340864a14805575f463a4bb92c6f3ef < prev    next >
Text File  |  2004-06-01  |  35KB  |  969 lines

  1. # The documentation is at the __END__
  2.  
  3. package Win32::OLE;
  4.  
  5. use strict;
  6. use vars qw($VERSION @ISA @EXPORT @EXPORT_OK @EXPORT_FAIL $AUTOLOAD
  7.         $CP $LCID $Warn $LastError $_NewEnum $_Unique);
  8.  
  9. $VERSION = '0.1701';
  10.  
  11. use Carp;
  12. use Exporter;
  13. use DynaLoader;
  14. @ISA = qw(Exporter DynaLoader);
  15.  
  16. @EXPORT = qw();
  17. @EXPORT_OK = qw(in valof with HRESULT EVENTS OVERLOAD
  18.                 CP_ACP CP_OEMCP CP_MACCP CP_UTF7 CP_UTF8
  19.         DISPATCH_METHOD DISPATCH_PROPERTYGET
  20.         DISPATCH_PROPERTYPUT DISPATCH_PROPERTYPUTREF);
  21. @EXPORT_FAIL = qw(EVENTS OVERLOAD);
  22.  
  23. sub export_fail {
  24.     shift;
  25.     my @unknown;
  26.     while (@_) {
  27.     my $symbol = shift;
  28.     if ($symbol eq 'OVERLOAD') {
  29.         eval <<'OVERLOAD';
  30.             use overload '""'     => \&valof,
  31.                          '0+'     => \&valof,
  32.                          fallback => 1;
  33. OVERLOAD
  34.     }
  35.     elsif ($symbol eq 'EVENTS') {
  36.         Win32::OLE->Initialize(Win32::OLE::COINIT_OLEINITIALIZE());
  37.     }
  38.     else {
  39.         push @unknown, $symbol;
  40.     }
  41.     }
  42.     return @unknown;
  43. }
  44.  
  45. unless (defined &Dispatch) {
  46.     # Use regular DynaLoader if XS part is not yet initialized
  47.     bootstrap Win32::OLE;
  48.     require Win32::OLE::Lite;
  49. }
  50.  
  51. 1;
  52.  
  53. ########################################################################
  54.  
  55. __END__
  56.  
  57. =head1 NAME
  58.  
  59. Win32::OLE - OLE Automation extensions
  60.  
  61. =head1 SYNOPSIS
  62.  
  63.     $ex = Win32::OLE->new('Excel.Application') or die "oops\n";
  64.     $ex->Amethod("arg")->Bmethod->{'Property'} = "foo";
  65.     $ex->Cmethod(undef,undef,$Arg3);
  66.     $ex->Dmethod($RequiredArg1, {NamedArg1 => $Value1, NamedArg2 => $Value2});
  67.  
  68.     $wd = Win32::OLE->GetObject("D:\\Data\\Message.doc");
  69.     $xl = Win32::OLE->GetActiveObject("Excel.Application");
  70.  
  71. =head1 DESCRIPTION
  72.  
  73. This module provides an interface to OLE Automation from Perl.
  74. OLE Automation brings VisualBasic like scripting capabilities and
  75. offers powerful extensibility and the ability to control many Win32
  76. applications from Perl scripts.
  77.  
  78. The Win32::OLE module uses the IDispatch interface exclusively.  It is
  79. not possible to access a custom OLE interface.  OLE events and OCX's are
  80. currently not supported.
  81.  
  82. Actually, that's no longer strictly true.  This module now contains
  83. B<ALPHA> level support for OLE events.  This is largely untested and the
  84. specific interface might still change in the future.
  85.  
  86. =head2 Methods
  87.  
  88. =over 8
  89.  
  90. =item Win32::OLE->new(PROGID[, DESTRUCTOR])
  91.  
  92. The new() class method starts a new instance of an OLE Automation object.
  93. It returns a reference to this object or C<undef> if the creation failed.
  94.  
  95. The PROGID argument must be either the OLE I<program id> or the I<class id>
  96. of the required application.  The optional DESTRUCTOR specifies a DESTROY-like
  97. method.  This can be either a CODE reference or a string containing an OLE
  98. method name.  It can be used to cleanly terminate OLE applications in case the
  99. Perl program dies.
  100.  
  101. To create an object via DCOM on a remote server you can use an array
  102. reference in place of PROGID.  The referenced array must contain the
  103. machine name and the I<program id> or I<class id>.  For example:
  104.  
  105.     my $obj = Win32::OLE->new(['my.machine.com', 'Program.Id']);
  106.  
  107. If the PROGID is a I<program id> then Win32::OLE will try to resolve the
  108. corresponding I<class id> locally.  If the I<program id> is not registered
  109. locally then the remote registry is queried.  This will only succeed if
  110. the local process has read access to the remote registry.  The safest
  111. (and fastest) method is to specify the C<class id> directly.
  112.  
  113. =item Win32::OLE->EnumAllObjects([CALLBACK])
  114.  
  115. This class method returns the number Win32::OLE objects currently in
  116. existance.  It will call the optional CALLBACK function for each of
  117. these objects:
  118.  
  119.     $Count = Win32::OLE->EnumAllObjects(sub {
  120.         my $Object = shift;
  121.         my $Class = Win32::OLE->QueryObjectType($Object);
  122.         printf "# Object=%s Class=%s\n", $Object, $Class;
  123.     });
  124.  
  125. The EnumAllObjects() method is primarily a debugging tool.  It can be
  126. used e.g. in an END block to check if all external connections have
  127. been properly destroyed.
  128.  
  129. =item Win32::OLE->FreeUnusedLibraries()
  130.  
  131. The FreeUnusedLibraries() class method unloads all unused OLE
  132. resources.  These are the libraries of those classes of which all
  133. existing objects have been destroyed.  The unloading of object
  134. libraries is really only important for long running processes that
  135. might instantiate a huge number of B<different> objects over time.
  136.  
  137. Be aware that objects implemented in Visual Basic have a buggy
  138. implementation of this functionality: They pretend to be unloadable
  139. while they are actually still running their cleanup code.  Unloading
  140. the DLL at that moment typically produces an access violation.  The
  141. probability for this problem can be reduced by calling the
  142. SpinMessageLoop() method and sleep()ing for a few seconds.
  143.  
  144. =item Win32::OLE->GetActiveObject(CLASS[, DESTRUCTOR])
  145.  
  146. The GetActiveObject() class method returns an OLE reference to a
  147. running instance of the specified OLE automation server.  It returns
  148. C<undef> if the server is not currently active.  It will croak if
  149. the class is not even registered.  The optional DESTRUCTOR method takes
  150. either a method name or a code reference.  It is executed when the last
  151. reference to this object goes away.  It is generally considered C<impolite>
  152. to stop applications that you did not start yourself.
  153.  
  154. =item Win32::OLE->GetObject(MONIKER[, DESTRUCTOR])
  155.  
  156. The GetObject() class method returns an OLE reference to the specified
  157. object.  The object is specified by a pathname optionally followed by
  158. additional item subcomponent separated by exclamation marks '!'.  The
  159. optional DESTRUCTOR argument has the same semantics as the DESTRUCTOR in
  160. new() or GetActiveObject().
  161.  
  162. =item Win32::OLE->Initialize([COINIT])
  163.  
  164. The Initialize() class method can be used to specify an alternative
  165. apartment model for the Perl thread.  It must be called B<before> the
  166. first OLE object is created.  If the C<Win32::OLE::Const> module is
  167. used then the call to the Initialize() method must be made from a BEGIN
  168. block before the first C<use> statement for the C<Win32::OLE::Const>
  169. module.
  170.  
  171. Valid values for COINIT are:
  172.  
  173.   Win32::OLE::COINIT_APARTMENTTHREADED  - single threaded
  174.   Win32::OLE::COINIT_MULTITHREADED      - the default
  175.   Win32::OLE::COINIT_OLEINITIALIZE      - single threaded, additional OLE stuff
  176.  
  177. COINIT_OLEINITIALIZE is sometimes needed when an OLE object uses
  178. additional OLE compound document technologies not available from the
  179. normal COM subsystem (for example MAPI.Session seems to require it).
  180. Both COINIT_OLEINITIALIZE and COINIT_APARTMENTTHREADED create a hidden
  181. top level window and a message queue for the Perl process.  This may
  182. create problems with other application, because Perl normally doesn't
  183. process its message queue.  This means programs using synchronous
  184. communication between applications (such as DDE initiation), may hang
  185. until Perl makes another OLE method call/property access or terminates.
  186. This applies to InstallShield setups and many things started to shell
  187. associations.  Please try to utilize the C<Win32::OLE-E<gt>SpinMessageLoop>
  188. and C<Win32::OLE-E<gt>Uninitialize> methods if you can not use the default
  189. COINIT_MULTITHREADED model.
  190.  
  191. =item OBJECT->Invoke(METHOD[, ARGS])
  192.  
  193. The Invoke() object method is an alternate way to invoke OLE
  194. methods.  It is normally equivalent to C<$OBJECT->METHOD(@ARGS)>.  This
  195. function must be used if the METHOD name contains characters not valid
  196. in a Perl variable name (like foreign language characters).  It can
  197. also be used to invoke the default method of an object even if the
  198. default method has not been given a name in the type library.  In this
  199. case use <undef> or C<''> as the method name.  To invoke an OLE objects
  200. native Invoke() method (if such a thing exists), please use:
  201.  
  202.     $Object->Invoke('Invoke', @Args);
  203.  
  204. =item Win32::OLE->LastError()
  205.  
  206. The LastError() class method returns the last recorded OLE
  207. error.  This is a dual value like the C<$!> variable: in a numeric
  208. context it returns the error number and in a string context it returns
  209. the error message.  The error number is a signed HRESULT value.  Please
  210. use the L<HRESULT(ERROR)> function to convert an unsigned hexadecimal
  211. constant to a signed HRESULT.
  212.  
  213. The last OLE error is automatically reset by a successful OLE
  214. call.  The numeric value can also explicitly be set by a call (which will
  215. discard the string value):
  216.  
  217.     Win32::OLE->LastError(0);
  218.  
  219. =item OBJECT->LetProperty(NAME,ARGS,VALUE)
  220.  
  221. In Win32::OLE property assignment using the hash syntax is equivalent
  222. to the Visual Basic C<Set> syntax (I<by reference> assignment):
  223.  
  224.     $Object->{Property} = $OtherObject;
  225.  
  226. corresponds to this Visual Basic statement:
  227.  
  228.     Set Object.Property = OtherObject
  229.  
  230. To get the I<by value> treatment of the Visual Basic C<Let> statement
  231.  
  232.     Object.Property = OtherObject
  233.  
  234. you have to use the LetProperty() object method in Perl:
  235.  
  236.     $Object->LetProperty($Property, $OtherObject);
  237.  
  238. LetProperty() also supports optional arguments for the property assignment.
  239. See L<OBJECT->SetProperty(NAME,ARGS,VALUE)> for details.
  240.  
  241. =item Win32::OLE->MessageLoop()
  242.  
  243. The MessageLoop() class method will run a standard Windows message
  244. loop, dispatching messages until the QuitMessageLoop() class method is
  245. called.  It is used to wait for OLE events.
  246.  
  247. =item Win32::OLE->Option(OPTION)
  248.  
  249. The Option() class method can be used to inspect and modify
  250. L<Module Options>.  The single argument form retrieves the value of
  251. an option:
  252.  
  253.     my $CP = Win32::OLE->Option('CP');
  254.  
  255. A single call can be used to set multiple options simultaneously:
  256.  
  257.     Win32::OLE->Option(CP => CP_ACP, Warn => 3);
  258.  
  259. =item Win32::OLE->QueryObjectType(OBJECT)
  260.  
  261. The QueryObjectType() class method returns a list of the type library
  262. name and the objects class name.  In a scalar context it returns the
  263. class name only.  It returns C<undef> when the type information is not
  264. available.
  265.  
  266. =item Win32::OLE->QuitMessageLoop()
  267.  
  268. The QuitMessageLoop() class method posts a (user-level) "Quit" message
  269. to the current threads message loop.  QuitMessageLoop() is typically
  270. called from an event handler.  The MessageLoop() class method will
  271. return when it receives this "Quit" method.
  272.  
  273. =item OBJECT->SetProperty(NAME,ARGS,VALUE)
  274.  
  275. The SetProperty() method allows to modify properties with arguments,
  276. which is not supported by the hash syntax.  The hash form
  277.  
  278.     $Object->{Property} = $Value;
  279.  
  280. is equivalent to
  281.  
  282.     $Object->SetProperty('Property', $Value);
  283.  
  284. Arguments must be specified between the property name and the new value:
  285.  
  286.     $Object->SetProperty('Property', @Args, $Value);
  287.  
  288. It is not possible to use "named argument" syntax with this function
  289. because the new value must be the last argument to SetProperty().
  290.  
  291. This method hides any native OLE object method called SetProperty().
  292. The native method will still be available through the Invoke() method:
  293.  
  294.     $Object->Invoke('SetProperty', @Args);
  295.  
  296. =item Win32::OLE->SpinMessageLoop
  297.  
  298. This class method retrieves all pending messages from the message queue
  299. and dispatches them to their respective window procedures.  Calling this
  300. method is only necessary when not using the COINIT_MULTITHREADED model.
  301. All OLE method calls and property accesses automatically process the
  302. message queue.
  303.  
  304. =item Win32::OLE->Uninitialize
  305.  
  306. The Uninitialize() class method uninitializes the OLE subsystem.  It
  307. also destroys the hidden top level window created by OLE for single
  308. threaded apartments.  All OLE objects will become invalid after this call!
  309. It is possible to call the Initialize() class method again with a different
  310. apartment model after shutting down OLE with Uninitialize().
  311.  
  312. =item Win32::OLE->WithEvents(OBJECT[, HANDLER[, INTERFACE]])
  313.  
  314. This class method enables and disables the firing of events by the
  315. specified OBJECT.  If no HANDLER is specified, then events are
  316. disconnected.  For some objects Win32::OLE is not able to
  317. automatically determine the correct event interface.  In this case the
  318. INTERFACE argument must contain either the COCLASS name of the OBJECT
  319. or the name of the event DISPATCH interface.  Please read the L<Events>
  320. section below for detailed explanation of the Win32::OLE event
  321. support.
  322.  
  323. =back
  324.  
  325. Whenever Perl does not find a method name in the Win32::OLE package it
  326. is automatically used as the name of an OLE method and this method call
  327. is dispatched to the OLE server.
  328.  
  329. There is one special hack built into the module: If a method or property
  330. name could not be resolved with the OLE object, then the default method
  331. of the object is called with the method name as its first parameter.  So
  332.  
  333.     my $Sheet = $Worksheets->Table1;
  334. or
  335.     my $Sheet = $Worksheets->{Table1};
  336.  
  337. is resolved as
  338.  
  339.     my $Sheet = $Worksheet->Item('Table1');
  340.  
  341. provided that the $Worksheets object doesnot have a C<Table1> method
  342. or property.  This hack has been introduced to call the default method
  343. of collections which did not name the method in their type library.  The
  344. recommended way to call the "unnamed" default method is:
  345.  
  346.     my $Sheet = $Worksheets->Invoke('', 'Table1');
  347.  
  348. This special hack is disabled under C<use strict 'subs';>.
  349.  
  350. =head2 Object methods and properties
  351.  
  352. The object returned by the new() method can be used to invoke
  353. methods or retrieve properties in the same fashion as described
  354. in the documentation for the particular OLE class (eg. Microsoft
  355. Excel documentation describes the object hierarchy along with the
  356. properties and methods exposed for OLE access).
  357.  
  358. Optional parameters on method calls can be omitted by using C<undef>
  359. as a placeholder.  A better way is to use named arguments, as the
  360. order of optional parameters may change in later versions of the OLE
  361. server application.  Named parameters can be specified in a reference
  362. to a hash as the last parameter to a method call.
  363.  
  364. Properties can be retrieved or set using hash syntax, while methods
  365. can be invoked with the usual perl method call syntax.  The C<keys>
  366. and C<each> functions can be used to enumerate an object's properties.
  367. Beware that a property is not always writable or even readable (sometimes
  368. raising exceptions when read while being undefined).
  369.  
  370. If a method or property returns an embedded OLE object, method
  371. and property access can be chained as shown in the examples below.
  372.  
  373. =head2 Functions
  374.  
  375. The following functions are not exported by default.
  376.  
  377. =over 8
  378.  
  379. =item HRESULT(ERROR)
  380.  
  381. The HRESULT() function converts an unsigned number into a signed HRESULT
  382. error value as used by OLE internally.  This is necessary because Perl
  383. treats all hexadecimal constants as unsigned.  To check if the last OLE
  384. function returned "Member not found" (0x80020003) you can write:
  385.  
  386.     if (Win32::OLE->LastError == HRESULT(0x80020003)) {
  387.         # your error recovery here
  388.     }
  389.  
  390. =item in(COLLECTION)
  391.  
  392. If COLLECTION is an OLE collection object then C<in $COLLECTION>
  393. returns a list of all members of the collection.  This is a shortcut
  394. for C<Win32::OLE::Enum->All($COLLECTION)>.  It is most commonly used in
  395. a C<foreach> loop:
  396.  
  397.     foreach my $value (in $collection) {
  398.         # do something with $value here
  399.     }
  400.  
  401. =item valof(OBJECT)
  402.  
  403. Normal assignment of Perl OLE objects creates just another reference
  404. to the OLE object.  The valof() function explictly dereferences the
  405. object (through the default method) and returns the value of the object.
  406.  
  407.     my $RefOf = $Object;
  408.     my $ValOf = valof $Object;
  409.         $Object->{Value} = $NewValue;
  410.  
  411. Now $ValOf still contains the old value wheras $RefOf would
  412. resolve to the $NewValue because it is still a reference to
  413. $Object.
  414.  
  415. The valof() function can also be used to convert Win32::OLE::Variant
  416. objects to Perl values.
  417.  
  418. =item with(OBJECT, PROPERTYNAME => VALUE, ...)
  419.  
  420. This function provides a concise way to set the values of multiple
  421. properties of an object.  It iterates over its arguments doing
  422. C<$OBJECT->{PROPERTYNAME} = $VALUE> on each trailing pair.
  423.  
  424. =back
  425.  
  426. =head2 Overloading
  427.  
  428. The Win32::OLE objects can be overloaded to automatically convert to
  429. their values whenever they are used in a bool, numeric or string
  430. context.  This is not enabled by default.  You have to request it
  431. through the OVERLOAD pseudoexport:
  432.  
  433.     use Win32::OLE qw(in valof with OVERLOAD);
  434.  
  435. You can still get the original string representation of an object
  436. (C<Win32::OLE=0xDEADBEEF>), e.g. for debugging, by using the
  437. C<overload::StrVal()> method:
  438.  
  439.     print overload::StrVal($object), "\n";
  440.  
  441. Please note that C<OVERLOAD> is a global setting.  If any module enables
  442. Win32::OLE overloading then it's active everywhere.
  443.  
  444. =head2 Events
  445.  
  446. The Win32::OLE module now contains B<ALPHA> level event support.  This
  447. support is only available when Perl is running in a single threaded
  448. apartment.  This can most easily be assured by using the C<EVENTS>
  449. pseudo-import:
  450.  
  451.     use Win32::OLE qw(EVENTS);
  452.  
  453. which implicitly does something like:
  454.  
  455.     use Win32::OLE;
  456.     Win32::OLE->Initialize(Win32::OLE::COINIT_OLEINITIALIZE);
  457.  
  458. The current interface to OLE events should be considered experimental
  459. and is subject to change.  It works as expected for normal OLE
  460. applications, but OLE control events often don't seem to work yet.
  461.  
  462. Events must be enabled explicitly for an OLE object through the
  463. Win32::OLE->WithEvents() class method.  The Win32::OLE module uses the
  464. IProvideClassInfo2 interface to determine the default event source of
  465. the object.  If this interface is not supported, then the user must
  466. specify the name of the event source explicitly in the WithEvents()
  467. method call.  It is also possible to specify the class name of the
  468. object as the third parameter.  In this case Win32::OLE will try to
  469. look up the default source interface for this COCLASS.
  470.  
  471. The HANDLER argument to Win32::OLE->WithEvents() can either be a CODE
  472. reference or a package name.  In the first case, all events will invoke
  473. this particular function.  The first two arguments to this function will
  474. be the OBJECT itself and the name of the event.  The remaining arguments
  475. will be event specific.
  476.  
  477.     sub Event {
  478.         my ($Obj,$Event,@Args) = @_;
  479.         print "Event triggered: '$Event'\n";
  480.     }
  481.     Win32::OLE->WithEvents($Obj, \&Event);
  482.  
  483. Alternatively the HANDLER argument can specify a package name.  When the
  484. OBJECT fires an event, Win32::OLE will try to find a function of the same
  485. name as the event in this package.  This function will be called with the
  486. OBJECT as the first argument followed again by the event specific parameters:
  487.  
  488.     package MyEvents;
  489.     sub EventName1 {
  490.         my ($Obj,@Args) = @_;
  491.         print "EventName1 event triggered\n";
  492.     }
  493.  
  494.     package main;
  495.     Win32::OLE->WithEvents($Obj, 'MyEvents', 'IEventInterface');
  496.  
  497. If Win32::OLE doesn't find a function with the name of the event then nothing
  498. happens.
  499.  
  500. Event parameters passed I<by reference> are handled specially.  They are not
  501. converted to the corresponding Perl datatype but passed as Win32::OLE::Variant
  502. objects.  You can assign a new value to these objects with the help of the
  503. Put() method.  This value will be passed back to the object when the event
  504. function returns:
  505.  
  506.     package MyEvents;
  507.     sub BeforeClose {
  508.         my ($self,$Cancel) = @_;
  509.         $Cancel->Put(1) unless $MayClose;
  510.     }
  511.  
  512. Direct assignment to $Cancel would have no effect on the original value and
  513. would therefore not command the object to abort the closing action.
  514.  
  515. =head2 Module Options
  516.  
  517. The following module options can be accessed and modified with the
  518. C<Win32::OLE->Option> class method.  In earlier versions of the Win32::OLE
  519. module these options were manipulated directly as class variables.  This
  520. practice is now deprecated.
  521.  
  522. =over 8
  523.  
  524. =item CP
  525.  
  526. This variable is used to determine the codepage used by all
  527. translations between Perl strings and Unicode strings used by the OLE
  528. interface.  The default value is CP_ACP, which is the default ANSI
  529. codepage.  Other possible values are CP_OEMCP, CP_MACCP, CP_UTF7 and
  530. CP_UTF8.  These constants are not exported by default.
  531.  
  532. =item LCID
  533.  
  534. This variable controls the locale idnetifier used for all OLE calls.
  535. It is set to LOCALE_NEUTRAL by default.  Please check the
  536. L<Win32::OLE::NLS> module for other locale related information.
  537.  
  538. =item Variant
  539.  
  540. This options controls how method calls and property accessors return
  541. values of type VT_CY and VT_DECIMAL are being returned.  By default
  542. VT_CY values are turned into strings and VT_DECIMAL values into
  543. floating point numbers.  If the C<Variant> option is enabled, these
  544. values are returned as Win32::OLE::Variant objects, just like VT_DATE
  545. and VT_ERROR values.  If the Win32::OLE::Variant module is also
  546. loaded, then all values should still behave as before in string and in
  547. numeric context.
  548.  
  549. The only reason that the C<Variant> behavior is not the default is that
  550. this is an incompatible change that might break existing programs.
  551.  
  552. =item Warn
  553.  
  554. This variable determines the behavior of the Win32::OLE module when
  555. an error happens.  Valid values are:
  556.  
  557.     0    Ignore error, return undef
  558.     1    Carp::carp if $^W is set (-w option)
  559.     2    always Carp::carp
  560.     3    Carp::croak
  561.  
  562. The error number and message (without Carp line/module info) are
  563. available through the C<Win32::OLE->LastError> class method.
  564.  
  565. Alternatively the Warn option can be set to a CODE reference.  E.g.
  566.  
  567.     Win32::OLE->Option(Warn => 3);
  568.  
  569. is equivalent to
  570.  
  571.     Win32::OLE->Option(Warn => \&Carp::croak);
  572.  
  573. This can even be used to emulate the VisualBasic C<On Error Goto
  574. Label> construct:
  575.  
  576.     Win32::OLE->Option(Warn =>  sub {goto CheckError});
  577.     # ... your normal OLE code here ...
  578.  
  579.   CheckError:
  580.     # ... your error handling code here ...
  581.  
  582. =item _NewEnum
  583.  
  584. This option enables additional enumeration support for collection
  585. objects.  When the C<_NewEnum> option is set, all collections will
  586. receive one additional property: C<_NewEnum>.  The value of this
  587. property will be a reference to an array containing all the elements
  588. of the collection.  This option can be useful when used in conjunction
  589. with an automatic tree traversal program, like C<Data::Dumper> or an
  590. object tree browser.  The value of this option should be either 1
  591. (enabled) or 0 (disabled, default).
  592.  
  593.     Win32::OLE->Option(_NewEnum => 1);
  594.     # ...
  595.     my @sheets = @{$Excel->Worksheets->{_NewEnum}};
  596.  
  597. In normal application code, this would be better written as:
  598.  
  599.     use Win32::OLE qw(in);
  600.     # ...
  601.     my @sheets = in $Excel->Worksheets;
  602.  
  603. =item _Unique
  604.  
  605. The C<_Unique> options guarantees that Win32::OLE will maintain a
  606. one-to-one mapping between Win32::OLE objects and the native COM/OLE
  607. objects.  Without this option, you can query the same property twice
  608. and get two different Win32::OLE objects for the same underlying COM
  609. object.
  610.  
  611. Using a unique proxy makes life easier for tree traversal algorithms
  612. to recognize they already visited a particular node.  This option
  613. comes at a price: Win32::OLE has to maintain a global hash of all
  614. outstanding objects and their corresponding proxies.  Identity checks
  615. on COM objects can also be expensive if the objects reside
  616. out-of-process or even on a different computer.  Therefore this option
  617. is off by default unless the program is being run in the debugger.
  618.  
  619. Unfortunately, this option doesn't always help.  Some programs will
  620. return new COM objects for even the same property when asked for it
  621. multiple times (especially for collections).  In this case, there is
  622. nothing Win32::OLE can do to detect that these objects are in fact
  623. identical (because they aren't at the COM level).
  624.  
  625. The C<_Unique> option can be set to either 1 (enabled) or 0 (disabled,
  626. default).
  627.  
  628. =back
  629.  
  630. =head1 EXAMPLES
  631.  
  632. Here is a simple Microsoft Excel application.
  633.  
  634.     use Win32::OLE;
  635.  
  636.     # use existing instance if Excel is already running
  637.     eval {$ex = Win32::OLE->GetActiveObject('Excel.Application')};
  638.     die "Excel not installed" if $@;
  639.     unless (defined $ex) {
  640.         $ex = Win32::OLE->new('Excel.Application', sub {$_[0]->Quit;})
  641.             or die "Oops, cannot start Excel";
  642.     }
  643.  
  644.         # get a new workbook
  645.         $book = $ex->Workbooks->Add;
  646.  
  647.     # write to a particular cell
  648.     $sheet = $book->Worksheets(1);
  649.     $sheet->Cells(1,1)->{Value} = "foo";
  650.  
  651.         # write a 2 rows by 3 columns range
  652.         $sheet->Range("A8:C9")->{Value} = [[ undef, 'Xyzzy', 'Plugh' ],
  653.                                            [ 42,    'Perl',  3.1415  ]];
  654.  
  655.         # print "XyzzyPerl"
  656.         $array = $sheet->Range("A8:C9")->{Value};
  657.     for (@$array) {
  658.         for (@$_) {
  659.         print defined($_) ? "$_|" : "<undef>|";
  660.         }
  661.         print "\n";
  662.     }
  663.  
  664.     # save and exit
  665.         $book->SaveAs( 'test.xls' );
  666.     undef $book;
  667.     undef $ex;
  668.  
  669. Please note the destructor specified on the Win32::OLE->new method.  It ensures
  670. that Excel will shutdown properly even if the Perl program dies.  Otherwise
  671. there could be a process leak if your application dies after having opened
  672. an OLE instance of Excel.  It is the responsibility of the module user to
  673. make sure that all OLE objects are cleaned up properly!
  674.  
  675. Here is an example of using Variant data types.
  676.  
  677.     use Win32::OLE;
  678.     use Win32::OLE::Variant;
  679.     $ex = Win32::OLE->new('Excel.Application', \&OleQuit) or die "oops\n";
  680.     $ex->{Visible} = 1;
  681.     $ex->Workbooks->Add;
  682.     # should generate a warning under -w
  683.     $ovR8 = Variant(VT_R8, "3 is a good number");
  684.     $ex->Range("A1")->{Value} = $ovR8;
  685.     $ex->Range("A2")->{Value} = Variant(VT_DATE, 'Jan 1,1970');
  686.  
  687.     sub OleQuit {
  688.         my $self = shift;
  689.         $self->Quit;
  690.     }
  691.  
  692. The above will put value "3" in cell A1 rather than the string
  693. "3 is a good number".  Cell A2 will contain the date.
  694.  
  695. Similarly, to invoke a method with some binary data, you can
  696. do the following:
  697.  
  698.     $obj->Method( Variant(VT_UI1, "foo\000b\001a\002r") );
  699.  
  700. Here is a wrapper class that basically delegates everything but
  701. new() and DESTROY().  The wrapper class shown here is another way to
  702. properly shut down connections if your application is liable to die
  703. without proper cleanup.  Your own wrappers will probably do something
  704. more specific to the particular OLE object you may be dealing with,
  705. like overriding the methods that you may wish to enhance with your
  706. own.
  707.  
  708.     package Excel;
  709.     use Win32::OLE;
  710.  
  711.     sub new {
  712.         my $s = {};
  713.         if ($s->{Ex} = Win32::OLE->new('Excel.Application')) {
  714.         return bless $s, shift;
  715.         }
  716.         return undef;
  717.     }
  718.  
  719.     sub DESTROY {
  720.         my $s = shift;
  721.         if (exists $s->{Ex}) {
  722.         print "# closing connection\n";
  723.         $s->{Ex}->Quit;
  724.         return undef;
  725.         }
  726.     }
  727.  
  728.     sub AUTOLOAD {
  729.         my $s = shift;
  730.         $AUTOLOAD =~ s/^.*:://;
  731.         $s->{Ex}->$AUTOLOAD(@_);
  732.     }
  733.  
  734.     1;
  735.  
  736. The above module can be used just like Win32::OLE, except that
  737. it takes care of closing connections in case of abnormal exits.
  738. Note that the effect of this specific example can be easier accomplished
  739. using the optional destructor argument of Win32::OLE::new:
  740.  
  741.     my $Excel = Win32::OLE->new('Excel.Application', sub {$_[0]->Quit;});
  742.  
  743. Note that the delegation shown in the earlier example is not the same as
  744. true subclassing with respect to further inheritance of method calls in your
  745. specialized object.  See L<perlobj>, L<perltoot> and L<perlbot> for details.
  746. True subclassing (available by setting C<@ISA>) is also feasible,
  747. as the following example demonstrates:
  748.  
  749.     #
  750.     # Add error reporting to Win32::OLE
  751.     #
  752.  
  753.     package Win32::OLE::Strict;
  754.     use Carp;
  755.     use Win32::OLE;
  756.  
  757.     use strict qw(vars);
  758.     use vars qw($AUTOLOAD @ISA);
  759.     @ISA = qw(Win32::OLE);
  760.  
  761.     sub AUTOLOAD {
  762.         my $obj = shift;
  763.         $AUTOLOAD =~ s/^.*:://;
  764.         my $meth = $AUTOLOAD;
  765.         $AUTOLOAD = "SUPER::" . $AUTOLOAD;
  766.         my $retval = $obj->$AUTOLOAD(@_);
  767.         unless (defined($retval) || $AUTOLOAD eq 'DESTROY') {
  768.         my $err = Win32::OLE::LastError();
  769.         croak(sprintf("$meth returned OLE error 0x%08x",$err))
  770.           if $err;
  771.         }
  772.         return $retval;
  773.     }
  774.  
  775.     1;
  776.  
  777. This package inherits the constructor new() from the Win32::OLE
  778. package.  It is important to note that you cannot later rebless a
  779. Win32::OLE object as some information about the package is cached by
  780. the object.  Always invoke the new() constructor through the right
  781. package!
  782.  
  783. Here's how the above class will be used:
  784.  
  785.     use Win32::OLE::Strict;
  786.     my $Excel = Win32::OLE::Strict->new('Excel.Application', 'Quit');
  787.     my $Books = $Excel->Workbooks;
  788.     $Books->UnknownMethod(42);
  789.  
  790. In the sample above the call to UnknownMethod() will be caught with
  791.  
  792.     UnknownMethod returned OLE error 0x80020009 at test.pl line 5
  793.  
  794. because the Workbooks object inherits the class C<Win32::OLE::Strict> from the
  795. C<$Excel> object.
  796.  
  797. =head1 NOTES
  798.  
  799. =head2 Hints for Microsoft Office automation
  800.  
  801. =over 8
  802.  
  803. =item Documentation
  804.  
  805. The object model for the Office applications is defined in the Visual Basic
  806. reference guides for the various applications.  These are typically not
  807. installed by default during the standard installation.  They can be added
  808. later by rerunning the setup program with the custom install option.
  809.  
  810. =item Class, Method and Property names
  811.  
  812. The names have been changed between different versions of Office.  For
  813. example C<Application> was a method in Office 95 and is a property in
  814. Office97.  Therefore it will not show up in the list of property names
  815. C<keys %$object> when querying an Office 95 object.
  816.  
  817. The class names are not always identical to the method/property names
  818. producing the object.  E.g. the C<Workbook> method returns an object of
  819. type C<Workbook> in Office 95 and C<_Workbook> in Office 97.
  820.  
  821. =item Moniker (GetObject support)
  822.  
  823. Office applications seem to implement file monikers only.  For example
  824. it seems to be impossible to retrieve a specific worksheet object through
  825. C<GetObject("File.XLS!Sheet")>.  Furthermore, in Excel 95 the moniker starts
  826. a Worksheet object and in Excel 97 it returns a Workbook object.  You can use
  827. either the Win32::OLE::QueryObjectType class method or the $object->{Version}
  828. property to write portable code.
  829.  
  830. =item Enumeration of collection objects
  831.  
  832. Enumerations seem to be incompletely implemented.  Office 95 application don't
  833. seem to support neither the Reset() nor the Clone() methods.  The Clone()
  834. method is still unimplemented in Office 97.  A single walk through the
  835. collection similar to Visual Basics C<for each> construct does work however.
  836.  
  837. =item Localization
  838.  
  839. Starting with Office 97 Microsoft has changed the localized class, method and
  840. property names back into English.  Note that string, date and currency
  841. arguments are still subject to locale specific interpretation.  Perl uses the
  842. system default locale for all OLE transaction whereas Visual Basic uses a
  843. type library specific locale.  A Visual Basic script would use "R1C1" in string
  844. arguments to specify relative references.  A Perl script running on a German
  845. language Windows would have to use "Z1S1".  Set the LCID module option
  846. to an English locale to write portable scripts.  This variable should
  847. not be changed after creating the OLE objects; some methods seem to randomly
  848. fail if the locale is changed on the fly.
  849.  
  850. =item SaveAs method in Word 97 doesn't work
  851.  
  852. This is an known bug in Word 97.  Search the MS knowledge base for Word /
  853. Foxpro incompatibility.  That problem applies to the Perl OLE interface as
  854. well.  A workaround is to use the WordBasic compatibility object.  It doesn't
  855. support all the options of the native method though.
  856.  
  857.     $Word->WordBasic->FileSaveAs($file);
  858.  
  859. The problem seems to be fixed by applying the Office 97 Service Release 1.
  860.  
  861. =item Randomly failing method calls
  862.  
  863. It seems like modifying objects that are not selected/activated is sometimes
  864. fragile.  Most of these problems go away if the chart/sheet/document is
  865. selected or activated before being manipulated (just like an interactive
  866. user would automatically do it).
  867.  
  868. =back
  869.  
  870. =head2 Incompatibilities
  871.  
  872. There are some incompatibilities with the version distributed by Activeware
  873. (as of build 306).
  874.  
  875. =over 8
  876.  
  877. =item 1
  878.  
  879. The package name has changed from "OLE" to "Win32::OLE".
  880.  
  881. =item 2
  882.  
  883. All functions of the form "Win32::OLEFoo" are now "Win32::OLE::Foo",
  884. though the old names are temporarily accomodated.  Win32::OLECreateObject()
  885. was changed to Win32::OLE::CreateObject(), and is now called
  886. Win32::OLE::new() bowing to established convention for naming constructors.
  887. The old names should be considered deprecated, and will be removed in the
  888. next version.
  889.  
  890. =item 3
  891.  
  892. Package "OLE::Variant" is now "Win32::OLE::Variant".
  893.  
  894. =item 4
  895.  
  896. The Variant function is new, and is exported by default.  So are
  897. all the VT_XXX type constants.
  898.  
  899. =item 5
  900.  
  901. The support for collection objects has been moved into the package
  902. Win32::OLE::Enum.  The C<keys %$object> method is now used to enumerate
  903. the properties of the object.
  904.  
  905. =back
  906.  
  907. =head2 Bugs and Limitations
  908.  
  909. =over 8
  910.  
  911. =item *
  912.  
  913. To invoke a native OLE method with the same name as one of the
  914. Win32::OLE methods (C<Dispatch>, C<Invoke>, C<SetProperty>, C<DESTROY>,
  915. etc.), you have to use the C<Invoke> method:
  916.  
  917.     $Object->Invoke('Dispatch', @AdditionalArgs);
  918.  
  919. The same is true for names exported by the Exporter or the Dynaloader
  920. modules, e.g.: C<export>, C<export_to_level>, C<import>,
  921. C<_push_tags>, C<export_tags>, C<export_ok_tags>, C<export_fail>,
  922. C<require_version>, C<dl_load_flags>,
  923. C<croak>, C<bootstrap>, C<dl_findfile>, C<dl_expandspec>,
  924. C<dl_find_symbol_anywhere>, C<dl_load_file>, C<dl_find_symbol>,
  925. C<dl_undef_symbols>, C<dl_install_xsub> and C<dl_error>.
  926.  
  927. =back
  928.  
  929. =head1 SEE ALSO
  930.  
  931. The documentation for L<Win32::OLE::Const>, L<Win32::OLE::Enum>,
  932. L<Win32::OLE::NLS> and L<Win32::OLE::Variant> contains additional
  933. information about OLE support for Perl on Win32.
  934.  
  935. =head1 AUTHORS
  936.  
  937. Originally put together by the kind people at Hip and Activeware.
  938.  
  939. Gurusamy Sarathy <gsar@activestate.com> subsequently fixed several
  940. major bugs, memory leaks, and reliability problems, along with some
  941. redesign of the code.
  942.  
  943. Jan Dubois <jand@activestate.com> pitched in with yet more massive redesign,
  944. added support for named parameters, and other significant enhancements.
  945. He's been hacking on it ever since.
  946.  
  947. Please send questions about problems with this module to the
  948. Perl-Win32-Users mailinglist at ActiveState.com.  The mailinglist charter
  949. requests that you put an [OLE] tag somewhere on the subject line (for OLE
  950. related questions only, of course).
  951.  
  952. =head1 COPYRIGHT
  953.  
  954.     (c) 1995 Microsoft Corporation. All rights reserved.
  955.     Developed by ActiveWare Internet Corp., now known as
  956.     ActiveState Tool Corp., http://www.ActiveState.com
  957.  
  958.     Other modifications Copyright (c) 1997-2000 by Gurusamy Sarathy
  959.     <gsar@activestate.com> and Jan Dubois <jand@activestate.com>
  960.  
  961.     You may distribute under the terms of either the GNU General Public
  962.     License or the Artistic License, as specified in the README file.
  963.  
  964. =head1 VERSION
  965.  
  966. Version 0.1701      28 August 2003
  967.  
  968. =cut
  969.