Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I store the result of a system command in a Perl variable?

$ cat test.pl my $pid = 5892; my $not = system("top -H -p $pid -n 1 | grep myprocess | wc -l"); print "not = $not\n"; $ perl test.pl 11 not = 0 $ 

I want to capture the result i.e. 11 into a variable. How can I do that?

like image 868
Lazer Avatar asked Oct 04 '10 11:10

Lazer


People also ask

How do you store the system command output in a variable?

To store the output of a command in a variable, you can use the shell command substitution feature in the forms below: variable_name=$(command) variable_name=$(command [option ...] arg1 arg2 ...) OR variable_name='command' variable_name='command [option ...]

What is QX in Perl?

PERL QX FUNCTION. Description. This function is a alternative to using back-quotes to execute system commands. For example, qx ls − l will execute the UNIX ls command using the -l command-line option. You can actually use any set of delimiters, not just the parentheses.

What does system do in Perl?

Perl's system() function executes a system shell command. Here the parent process forks a child process, and then waits for the child process to terminate. The command will either succeed or fail returning a value for each situation.


2 Answers

From Perlfaq8:

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`; 

There are many ways to execute external commands from Perl. The most commons with their meanings are:

  • system() : you want to execute a command and don't want to capture its output
  • exec: you don't want to return to the calling perl script
  • backticks : you want to capture the output of the command
  • open: you want to pipe the command (as input or output) to your script

Also see How can I capture STDERR from an external command?

like image 101
Nikhil Jain Avatar answered Sep 18 '22 22:09

Nikhil Jain


The easiest way is to use the `` feature in Perl. This will execute what is inside and return what was printed to stdout:

 my $pid = 5892;  my $var = `top -H -p $pid -n 1 | grep myprocess | wc -l`;  print "not = $var\n"; 

This should do it.

like image 27
Peter Tillemans Avatar answered Sep 19 '22 22:09

Peter Tillemans