On 17.4.2014 9:24, Sergei Steshenko wrote:
From: kmx <k...@atlas.cz>
To: win32-vanilla@perl.org
Sent: Thursday, April 17, 2014 10:14 AM
Subject: Re: Run an external program and capture its output

On 17.4.2014 8:47, John Emmas wrote:

Firstly, please forgive me if this isn't the right place for asking this 
question.  I tried a couple of programmer's forums but up to now, my question 
hasn't even gained one answer!  And yet it seems like a simple (and probably 
very common) requirement.  I'm hoping that someone here will take pity on me!

I've been using Strawberry perl for about 6 months and I'm generally happy with 
it.  The one thing I just can't seem to make it do is to run an external 
program and capture that program's output to a file.  I came across perl's 
'system' command.  Let's say I add these lines to a perl script:-

         @my_command = ( "the_exe_name", "arg1", "arg2", "etc" );

If I now open a DOS window and run the perl script, sure enough, it runs 'the_exe_name'.  
And if my exe produces any text output I can see that output in my DOS window..  Suppose 
my perl script is called "my_perl_script.pl".  If I try to redirect its text 
output (like this) something interesting happens:-

         my_perl_script.pl > output.txt

The above seems to work in Windows 7.  However, it doesn't work in Windows 8 or Windows 
XP.  In both cases, the file "output.txt" does get created.  And in both cases 
I no longer see the exe's output text in my DOS window (i.e. as if it's getting 
redirected to the file).  But at the end of the process (in both cases) output.txt will 
be an empty file.  :-(

My next thought was to handle any redirection within the actual perl script - 

         @my_command = ( "the_exe_name", "arg1", "arg2", "etc" ">", 
"output.txt" );

Unfortunately, that doesn't seem to work either (again, it always creates an 
empty file).

Is there a way to achieve this using Strawberry perl?  Or am I making some 
rookie mistake here?  Admittedly I'm not very experienced with perl but I'm 
amazed that such a simple task seems to defeat it  :-(

my $output = `the_exe_name arg1 arg2`;

Or have a look at https://metacpan.org/pod/IPC::Run3

use IPC::Run3;
my $output;
run3(["the_exe_name", "arg1", "arg2", "etc"], undef, \$output);


FWIW, the

my $output = `the_exe_name arg1 arg2`;

way is to capture just STDOUT - _not_ STDERR. Regardless of OS.

I do not remember what 'IPC::Run3' WRT STDERR.

IPC::Run3 works AFAIK like this:

run3(["the_exe_name", "arg1", "arg2", "etc"], undef, \$std_out_and_err);
run3(["the_exe_name", "arg1", "arg2", "etc"], undef, \$std_out, \$std_err);


Reply via email to