$ 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
$
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?
Use backtick for system commands which helps to store their result into Perl variable.
my $pid = 5892; my $not = ``top -H -p $pid -n 1 | grep myprocess | wc -l`; print "not = $not\n";
Try using qx{command}
rather than backticks. To me, it's a bit better because: you can do SQL with it and not worry about escaping quotes and such. Depending on the editor and screen, my old eyes tend to miss the tiny back ticks, and it shouldn't ever have an issue with being overloaded like using angle brackets versus glob.
Using backtick
or qx
helps, thanks everybody for the answers. However, I found that if you use backtick
or qx
, the output contains trailing newline and I need to remove that. So I used chomp
.
chomp($host = `hostname`);
chomp($domain = `domainname`);
$fqdn = $host.".".$domain;
More information here: http://irouble.blogspot.in/2011/04/perl-chomp-backticks.html
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.