$ 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?
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 ...]
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.
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.
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:
Also see How can I capture STDERR from an external command?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With