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

How do I parse multi-line output to a system command? For example, I have a list of system names I want to get the IP address using ‘nslookup’. When I use this approach the print statement prints all 5 lines of the nslookup command. It seems no matter how I reference $totalArray I always get all 5 lines of output.

my $totalArray = system ( "nslookup", "$nodeName"); my @totalArraySplit = split(":", $totalArray); print STDOUT ("$totalArraySplit[1]\n");

How do I capture the multi-line output and split it into separate lines I can reference or into a multi-dimensional array?

Replies are listed 'Best First'.
Re: capturing and parsing multiline output
by ikegami (Patriarch) on Feb 24, 2009 at 15:52 UTC

    The return value of system isn't what you think it is. You need to use something else, such as backticks (qx//).

    Or in this case, gethostbyname.

      Thanks for the tips. Yes, gethostbyname() solved the initial problem and is much quicker. Using qx{ } also gave me what I was looking for on parsing multi-line output. Thanks again!

Re: capturing and parsing multiline output
by zentara (Cardinal) on Feb 24, 2009 at 15:59 UTC
Re: capturing and parsing multiline output
by dwm042 (Priest) on Feb 24, 2009 at 19:49 UTC
    This is to some extent peripheral to your question, but if you have a version of 'dig' that supports the +short option, you'll get a simpler list of data to parse.

    For example:

    C:\dig>dig www.cnnsi.com +short 64.236.29.106 64.236.29.107 157.166.255.22 157.166.255.23 64.236.22.106 64.236.22.107 C:\dig>nslookup www.cnnsi.com Server: ltc1usdc1.us.ceridian.hrs Address: 10.2.69.11 Non-authoritative answer: Name: www.cnnsi.com Addresses: 64.236.29.106, 64.236.29.107, 157.166.255.22, 157.166.255. +23 64.236.22.106, 64.236.22.107
Re: capturing and parsing multiline output
by hbm (Hermit) on Feb 24, 2009 at 16:26 UTC

    You could do something like this:

    use strict; use warnings; my $nodeName = "www.perlmonks.org"; open(NS,"nslookup $nodeName|") or die; my @ns = grep {chomp; s|^.*:\s*||; $_} <NS>; close(NS); print join("\n",@ns), "\n"; # or "$ns[3]\n", etc.