Beefy Boxes and Bandwidth Generously Provided by pair Networks
Pathologically Eclectic Rubbish Lister

assigning system command output to a variable

by Anonymous Monk
on Sep 02, 2003 at 21:38 UTC ( #288448=perlquestion: print w/replies, xml ) Need Help??

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

hope one of you experts could help me out. i am trying to assign a system command and use a regular expression to pipe its out. the result of this i wish to assign into a variable which i then use in an if statement. the problem is assigining the value to a variable. example:
$sample = system("./my_command"); #the system call returns a string li +ke "Intel CPU" if ($sample = "Intel CPU") { print "Intel CPU Found"; } else { exit(0); }
the problem is $sample has a value = 0 where am i wrong?

janitored by ybiC: balanced <code> tags around code sample, as per Monastery convention

Replies are listed 'Best First'.
Re: assigning system command output to a variable
by Paladin (Vicar) on Sep 02, 2003 at 21:48 UTC
    system doesn't return the output of the command, it returns the exit status, as the docs say. To get the output you need to use backticks `` or qx// which are explained in more detail in perldoc perlop.

    Also, = is the assignment operator. Use eq to compare strings for equality.

Re: assigning system command output to a variable
by bobn (Chaplain) on Sep 02, 2003 at 21:43 UTC

    $sample = `./my_command`;
    The return code for system is only a code for success or failure.

    --Bob Niederman,

    All code given here is UNTESTED unless otherwise stated.

Re: assigning system command output to a variable
by Rex(Wrecks) (Curate) on Sep 02, 2003 at 21:50 UTC
    From putting "system" into the search bar at the top of the page:

    "The return value is the exit status of the program as returned by the wait() call. To get the actual exit value divide by 256. See also exec. This is NOT what you want to use to capture the output from a command, for that you should use merely backticks or qx//, as described in `STRING`."

    From looking up "backticks" I got a whole list of nodes that should put you on the right path.

    The reason I explained this is to show how easy it is to get information on this site if you just try :)

    "Nothing is sure but death and taxes" I say combine the two and its death to all taxes!
Re: assigning system command output to a variable
by anoxer (Initiate) on Sep 02, 2003 at 22:13 UTC
    thanks for all your inputs. i got it to work :)

Log In?

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

How do I use this? | Other CB clients
Other Users?
Others browsing the Monastery: (7)
As of 2020-07-16 17:35 GMT
Find Nodes?
    Voting Booth?

    No recent polls found