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

Hello there!

I need get the output from runing a script, so I used:
if (! open(OUTPUT, "$myScript |")) { # handle error }
OUTPUT is now a handler for the output generated by the script.
Now, I need also the exit status returned from the script, which I can get by:
$exitStatus = system($script);
But this won't give me the output from the script.
Is there an effiecient way to get both the exit status and the output from the script (without using a temporary file)?

Thanks

Hotshot

Replies are listed 'Best First'.
Re: system() and output
by ctilmes (Vicar) on Aug 10, 2003 at 16:15 UTC
    After reading what you want from OUTPUT, close OUTPUT returns false if $myScript fails or exits with non-zero.

    It also leaves the exit status in $?.

    see perldoc -f close for more information.

    Or you can use backquotes my $output = `$myScript`; which also leaves exit status in $?.

      In your first suggestion, you said:

      close OUTPUT returns false if $myScript fails or exits with non-zero

      myScript returns 0 on success and non zero on failure, which is the opposite of what close() returns, what is returned on success of myScript and does the non-zero you mentioned are myScript exit statuses?

      And another thing, in your second suggestion, does $output holds the stdout from myScript?

      Thanks again

      Hotshot
Re: system() and output
by BrowserUk (Patriarch) on Aug 10, 2003 at 16:28 UTC

    The easiest way would be to use IPC::Open2. This returns the pid of the process. Once you have the pid, you can use waitpid to retrieve the status. It is returned in perlvar:$?. You need to shift this >> 8 in order to extract the status value.

    P:\test>type test.pl #! perl -slw print 'Hello world'; exit 12; P:\test>perl -de1 Loading DB routines from perl5db.pl version 1.19 Editor support available. Enter h or `h h' for help, or `perldoc perldebug' for more help. main::(-e:1): 1 DB<1> use IPC::Open2 DB<2> $pid = open2( IN, OUT, 'perl58.exe test.pl') or warn $!; DB<3> print <IN>; Hello world DB<4> waitpid $pid, 0 DB<5> print $? >> 8; DB<6> 12

    Examine what is said, not who speaks.
    "Efficiency is intelligent laziness." -David Dunham
    "When I'm working on a problem, I never think about beauty. I think only how to solve the problem. But when I have finished, if the solution is not beautiful, I know it is wrong." -Richard Buckminster Fuller
    If I understand your problem, I can solve it! Of course, the same can be said for you.