use strict; use warnings; use Win32::OLE; use File::Spec::Functions qw/catfile/; my $dir_path = $ARGV[0] or die "No directory argument given\n"; { open my $dir, $dir_path or die "Couldn't open $dir_path: $!\n"; # We only have to launch Word once before the loop and can keep it open # to improve performance... my $word = Win32::OLE->new('Word.Application', 'Quit') or die "Couldn't launch Word: " . Win32::OLE->LastError . "\n"; $word->{Visible} = $debug; while (my $file_name = readdir $dir) { next unless ($file_name =~ /\.doc$/i); my $file_path = catfile($dir_path, $file_name); if (my $document = $word->Documents->Open($file_path)) { eval { my $text1 = $document->FormFields('Text1')->Result; my $text18 = $document->FormFields('Text18')->Result; my $text20 = $document->FormFields('Text20')->Result; print "File($file_path) {\n text1: $text1,\n text18: $text18,\n text20: $text20\n}\n" }; warn "Error processing $file_name: $@\n" if ($@); $document->Close(); } else { warn "Couldn't open $file_name: " . Win32::OLE->LastError . "\n"; } } # Neither $dir nor $word have to be closed explicitly as they are both local objects whose # refcount drops to zero here and their destructors will close them as desired. }