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

hello

how can I redirect the output of a program and get the exit code too?

thanks

2006-02-22 Retitled by g0n, as per Monastery guidelines
Original title: 'redirection'

  • Comment on how can I redirect the output of a program and get the exit code too?

Replies are listed 'Best First'.
Re: how can I redirect the output of a program and get the exit code too?
by grinder (Bishop) on Jun 22, 2004 at 11:44 UTC

    Use backticks (or the qx// quoting mechanism) to launch the program and capture its output. You can obtain the exit code in the variable $?. It requires a bit of munging to pull out the three pieces of information it encodes. See perlvar for more information. The following code should help you get started.

    #! /usr/bin/perl -w my @output = `@ARGV`; print "Error code is $?\nOutput is ", @output, "\n";

    Run it with the name of the command (and its arguments) you want to execute. If the command you want to run requires its own redirections, or if you need to capture both the standard output and error streams, things get considerably trickier. It can be done albeit with a bit more code.

    - another intruder with the mooring of the heat of the Perl

      Thanks, it works.
      
      and how can I get the output continuously?
      it gives me the output after the command has been executed?
      
      like this:
      
      open (OUTPUT, "command |"); while (<OUTPUT>) #do something with output }
      can I use $? here too?

        Yes you can, but only if you call close OUTPUT before. The close function will put the return value to $?.

Re: how can I redirect the output of a program and get the exit code too?
by EvdB (Deacon) on Jun 22, 2004 at 11:15 UTC
    If you are after the exit code then I am assuming that the redirection you have in mind is on the terminal. This is not really a perl thing and dependent on your shell. Try typing help and going from there. Below are a few pointers for bash on linux though:
    $ perl buggy_code.pl > /dev/null # Send all nonwarnings to bit bin $ perl buggy_code.pl 2> errors.txt # send errors to a file

    --tidiness is the memory loss of environmental mnemonics