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

Hi all, I want to collect the output of a system() - I use system to skip the shell, but I found I am in some trouble to get the output of the program back...anyone can help?

Replies are listed 'Best First'.
Re: collect output of system()
by pc88mxer (Vicar) on Feb 27, 2008 at 16:21 UTC
    If you want to completely avoid invoking a shell, try using IPC::Open2 (or IPC::Open3 if you also need stderr.) Using backticks will spawn a shell (there really should be a multi-argument form of backticks.)

    Update: Here is a code fragment to do this:

    use IPC::Open2; use File::Temp; my ($fh, $path) = tempfile(); unlink($path); # automatically releases storage on exit my $pid = open2($fh, \*STDIN, ’some', 'cmd', 'and', 'args'); waitpid $pid, 0; # wait for child to exit # now you can read the child's output from $fh
Re: collect output of system()
by jeanluca (Deacon) on Feb 27, 2008 at 16:05 UTC
    I haven't used system() a lot, but I know you can easily collect the output like
    my @output = `ls /tmp` ;
    for example!

    Cheers
    Luca
Re: collect output of system()
by McDarren (Abbot) on Feb 27, 2008 at 16:23 UTC
    From perldoc -f system:
    The return value is the exit status of the program as returned by the "wait" call. To get the actual exit value, shif +t right by eight (see below). See also "exec". This is not wha +t you want to use to capture the output from a command, for t +hat you should use merely backticks or "qx//", as described in "`STRING`" in perlop.

    So, if you are interested in the output of the external command, you need to use backticks or qx.

    Note that system does not "skip" the shell at all.

    Also, for portability sake, it's best to look for a builtin or module that will do what you want, rather than forking to the shell. Whether or not one is available, depends on what you are doing.

    Cheers,
    Darren :)

      Calling system with multiple arguments will skip the shell, at least under Unix systems. When called with a single argument the shell will also be skipped if there are no shell meta-characters in the argument.