tags:

views:

95

answers:

2
$ 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?

+2  A: 

the easiest way is to use the `` feature in perl. The 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.

Peter Tillemans
@Peter: Is the $pid substitution within backtics a new feature? Can't get it to work with `v5.6.1`.
Lazer
This has worked as far as I can remember.e.g. try : `perl -e '$a="Hello"; print \`echo $a\`'`
Peter Tillemans
+7  A: 

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?

Nikhil Jain
thanks @Nikhil.
Lazer