0

I am a newbie in Perl Scripting. I am working on code in which I have to get CPU utilization. I am trying to run a command and then get the output in a variable. But when I try to print the variable I get nothing on the scree.

Command works fine in the terminal and gives me an output. ( I am using Eclipse ).

my $CPUusageOP;
$CPUusageOP = qx(top -b n 2 -d 0.01 | grep 'Cpu(s)' | tail -n 1 | gawk '{print $2+$4+$6}'); 
print "O/P of top command ", $CPUusageOP;

Output I get is :

    O/P of top command

Expected output :

    O/P of top command 31.4

Thanks.

SarveshD
  • 5
  • 1
  • 2
  • 2
    what's the point of a Perl script calling `grep`, `tail` and `awk`? I bet you can do all of it in `perl` or `awk`. – fedorqui Jan 06 '15 at 09:38

2 Answers2

2

qx() will interpolate $2 etc in your gawk, which you would have known if you had used warnings

use strict;
use warnings;

So you need to escape them:

... gawk '{print \$2+\$4+\$6}'); 

Also, of course, this is a silly thing to do in Perl. You can do all of that, except top (which may still be available in some module). E.g.:

my @lines = grep { /\QCpu(s)/ } qx(top -b n 2 -d 0.01);
my $CPUusageOP = $lines[-1];
$CPUusageOP = ( split ' ', $CPUusageOP )[1,3,5];

I cannot remember if awk starts the field designations with $1 or $0, but tweak it as you like.

TLP
  • 66,756
  • 10
  • 92
  • 149
  • 1
    well explained and detailed answer. In `awk`, `$0` refers to the current record (line, normally), whereas `$1` is the 1st field, `$2` the second, ... – fedorqui Jan 06 '15 at 09:47
  • 1
    You can just use `pop @{[ grep ... ]}` to save a line. – Tom Fenech Jan 06 '15 at 09:54
1

You don't need to use any external tool than top. Perl can do the rest:

#!/usr/bin/perl
use warnings;
use strict;

my $line;
open my $TOP, '-|', qw( top -b n 2 -d 0.01 ) or die $!;
while (<$TOP>) {
  $line = $_ if /Cpu\(s\)/;
}
my ($us, $ni, $wa) = (split ' ', $line)[1, 3, 5];
{   no warnings 'numeric';
    print $us + $ni + $wa, "\n";
}
choroba
  • 231,213
  • 25
  • 204
  • 289