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

I want to put the output of a command into an array, so
that I can operate on these output. The following is my
approach; but I feel it's very awkful. Do you have any
good ideas? Thanks in advance.

my $tmpfile = rand(); system("netstat > $tmpfile"); open(MYIN, "$tmpfile"); @connectInfo = <MYIN>; close(MYIN); unlink($tmpfile); # The following codes work on @connectInfo

Replies are listed 'Best First'.
Re: catch the output of a command
by dvergin (Monsignor) on Aug 01, 2001 at 19:31 UTC
    You are looking for backticks. The single line:      @connectInfo = `netstat`; ought to produce the same result as your code. Or:      @connectInfo = qx(netstat); means the same thing. Go to perlman:perlop and search for the second occurance of 'qx' to read a full discussion.

    Update: Note that the phrase "You're confusing the purpose of system()..." in tachyon's response is not directed at you. It is directed to the question it follows. You have used system() in a correct manner to produce a working but (as you suggested) un-Perlish bit of code.

    HTH... david

Re: catch the output of a command
by tachyon (Chancellor) on Aug 01, 2001 at 19:33 UTC

    Here is the answer from perlfaq8

    Why can't I get the output of a command with system()? You're confusing the purpose of system() and backticks (``). system() runs a command and returns exit status information (as a 16 bit value: the low 7 bits are the signal the process died from, if any, and the high 8 bits are the actual exit value). Backticks (``) run a command and return what it sent to STDOUT. $exit_status = system("mail-users"); $output_string = `ls`;

    Update

    This is the verbatim FAQ test. There is nothing per se wrong with your use of system in the example. I was to lazy to do more than cut and paste this.

    cheers

    tachyon

    s&&rsenoyhcatreve&&&s&n.+t&"$'$`$\"$\&"&ee&&y&srve&&d&&print

Re: catch the output of a command
by maverick (Curate) on Aug 01, 2001 at 21:57 UTC
    You can also do it like
    open(MYIN,"netstat |") || die "Can't netstat: $!"; @connectInfo = <MYIN>; . . .
    The advantage with this is that you get to check the status of the command.

    /\/\averick