http://www.perlmonks.org?node_id=814025

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

Is there a way to send the output of a unix command to a variable in Perl? I'm trying to have a while loop read in input, assign it to a variable and then have that variable be the input for the unix command. This is what I have:

#!/usr/bin/perl -w open(LIST, "list"); while(<LIST>) { @nodes=(<LIST>); chomp; my $nodename=`nslookup $_ | awk -F Name: '{ print $2 }'`; print $nodename; } close(LIST);

When I run it, it can't get past the '|' in the nslookup command. Thanks to all who can help.

Replies are listed 'Best First'.
Re: Assigning output of unix command to a variable
by almut (Canon) on Dec 23, 2009 at 01:25 UTC

    Not really sure why it doesn't get past the '|' (works fine here), but what looks suspicious is the @nodes=(<LIST>); as this reads everything from the second line onwards into an array which you never use in the loop. As a result, there would only be one call to nslookup with $_ holding the first line of the input file. Not sure if that's intended.

    Independently of that, you probably want to escape the $2 in the awk command, because backticks do interpolate variables... i.e.

    my $nodename=`nslookup $_ | awk -F Name: '{ print \$2 }'`;
      Thank you very much. You were right. As soon as I eacaped the '$' it worked perfectly!!!
Re: Assigning output of unix command to a variable
by bichonfrise74 (Vicar) on Dec 23, 2009 at 01:34 UTC
    What do you mean by "can't get past the '|' in the nslookup"? Consider this example.
    #!/usr/bin/perl use strict; my $node = qx( nslookup www.perlmonks.org | awk -F Name: '{ print \$2 }' ); print $node;
Re: Assigning output of unix command to a variable
by ikegami (Patriarch) on Dec 23, 2009 at 01:36 UTC

    Is the only problem that you forgot to escape the $ in $2? $2 is getting interpolated just like $_.

    ( Oops, I must have had this node open a while since almut already said this a while ago, and she caught a problem I missed. )