views:

28

answers:

2

I'm using IPC::System::Simple:runx to execute system commands and die on unexpected return values. The problem is that the commands output is printed to the shell.

  1. How can I avoid printing this output?
  2. How can I avoid printing this output but getting it into a perl variable?

UPDATE

3) How can I print this output iff the execution fails?

+2  A: 

The capture() command? Or capturex().

Quoted from link:

Exception handling

In the case where the command returns an unexpected status, both run and capture will throw an exception, which if not caught will terminate your program with an error.

Capturing the exception is easy:

eval {
    run("cat *.txt");
};

if ($@) {
    print "Something went wrong - $@\n";
}

See the diagnostics section below for more details.

colithium
Thanks, but is `capture` identical to `runx` as far as for the execution stage (the socu says that `catpure` works like backticks while `run` works like `system`)? Can I print what was captured only upon failure?
David B
See the edit I just made.
colithium
Thanks. Apparently `capturex` does by default exactly what I want: if everything goes fine it is silent, if an error (i.e. unexpected return value etc.) occurs, it dies but first prints the output of the command along with its own message. Great!
David B
A: 

If a module does behave very nasty and prints directly to STDOUT you can always redirect STDOUT to something else. This sort of a hack but some modules require it.

# Save STDOUT for restore later
open(OLD_STDOUT, ">>&STDOUT");
open(STDOUT, ">/some/file/or/dev/null");
# call your module
# Restore STDOUT
open(STDOUT, ">>&OLD_STDOUT");
tex