Perl: capture external command output, with or without a subshell

Discussion in 'all things UNIX' started by Gullible Jones, Dec 28, 2014.

  1. Gullible Jones

    Gullible Jones Registered Member

    Joined:
    May 16, 2013
    Posts:
    1,461
    This is kind of obvious in retrospect; but just FYI, if you want to capture external command outputs in Perl just like in the shell (and load them into variables etc.) you can open STDOUT for input via another file handle:

    Code:
    open $capture, "<&STDOUT";
    # Note that invoking system() on a list does not spawn a subshell
    system(qw(echo foo bar baz));
    chomp($foo = <$capture>);
    
    if ($foo == "foo bar baz") {
            print "Got it!\n";
    }
    
    will print

    Code:
    foo bar baz
    Got it!
    
    Among other things this might provide an alternative to backticks (which spawn a subshell, which may not be desirable).

    This should be doable easily in other languages (in fact Python seems to have much better facilities for it, go figure). Point is though, if an external command's output is not piped or redirected, it goes to STDOUT and STDERR, and you can read from those just like from any other file descriptors - and then load the data into variables to use however you want.

    Edit: and yeah, like I said this should have been obvious in retrospect. But Googling for ways of grabbing command output without backticks, there are lots of threads where nobody mentions anything like this, so...
     
  2. Gullible Jones

    Gullible Jones Registered Member

    Joined:
    May 16, 2013
    Posts:
    1,461
    Last edited: Dec 28, 2014
Loading...