http://www.perlmonks.org?node_id=86540

particle has asked for the wisdom of the Perl Monks concerning the following question:

this question has been asked and answered many times. but every answer has left me wanting something more. there must be something i'm missing, what is it?

i need to capture STDOUT, STDERR, and a return code from a 3rd party executable. i have code samples below of each method. i can't include the 3rd party exe, so i wrote a little perl code~

#!/usr/bin/perl # return.pl print STDERR "err1!\nerr2!\n"; print STDOUT "out!\nout again!\n"; exit 1;
i figured my best bet was IPC::Open3, but this does not give me the return code. even $? is set to the pid. here's a little code sample~
#!/usr/bin/perl # test1.pl use IPC::Open3; $n = "\n"; open( OUTPUT, ">&STDOUT" ) or die "Can't dup STDOUT to OUTPUT: $!$n"; open( OUTERR, ">&STDERR" ) or die "Can't dup STDERR to OUTERR: $!$n"; eval { $pid = open3("<&STDIN", \*OUTPUT, \*OUTERR, 'perl return.pl') } +; $@ && die "ERROR: $@$n"; @results = <OUTPUT>; @errors = <OUTERR>; close OUTPUT; close OUTERR; print "---pid$n"; print $pid . $n; print "---\$?$n"; print $? . $n; print "---results$n"; foreach(@results) { print $_ . $n }; print "---errors$n"; foreach(@errors) { print $_ . $n };
here's the output:
---pid 1480 ---$? 1480 ---results out! out again! ---errors err1! err2
as you can see, i can capture STDOUT and STDERR fine, but i can't find a way to get the exit code. $@ is the exit code from open3, should something disasterous happen. not the exit code from the executed code 'perl return.pl'.

i also tried system, to no avail~

#!/usr/bin/perl -w # test2.pl $n = "\n"; eval{ open( OUTPUT, "+>&STDOUT" ) or die "Can't dup STDOUT to OUTPUT: $!$n"; open( OUTERR, "+>&STDERR" ) or die "Can't dup STDERR to OUTERR: $!$n"; $return = system('perl', 'return.pl'); chomp ( @results = <OUTPUT> ); chomp ( @errors = <OUTERR> ); close OUTPUT; close OUTERR; }; $@ && die "ERROR: $@$n"; print "---return$n"; print $return>>8 , $n; print "---results$n"; foreach(@results) { print $_ . $n }; print "---errors$n"; foreach(@errors) { print $_ . $n };
and here's it's output:
err1! err2 out! out again! ---return 1 ---results ---errors
here i get the return code (GOOD!), but the output is not going being redirected. this looks more promising, but i'm tired so i've come for help.

the relevant links i found are listed below, for reference:

I want to capture a programs output AND I want the return status
Changing the name of STDOUT...
How can I redirect STDOUT and STDERR from a program on WIN32?
IPC::Open3
perlfunc:system

what am i missing?

=Particle