Beefy Boxes and Bandwidth Generously Provided by pair Networks
Problems? Is your data what you think it is?
 
PerlMonks  

Assigning output of unix command to a variable

by ksermas (Initiate)
on Dec 23, 2009 at 00:37 UTC ( #814025=perlquestion: print w/ replies, xml ) Need Help??
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.

Comment on Assigning output of unix command to a variable
Download Code
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 (Pope) 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. )

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://814025]
Approved by toolic
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others examining the Monastery: (8)
As of 2014-10-02 12:10 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    What is your favourite meta-syntactic variable name?














    Results (56 votes), past polls