On Friday 07 December 2007 04:36, [EMAIL PROTECTED] 
wrote:
> Hi,

Hello,

> I am not very good at perl however our systems use it and I am trying
> to write a few scripts to help our staff.
>
> I am trying to calculate the average CPU utilisation from a log file
> which is automatically generated.
>
> The columns are space seperated rather than comma.
>
> I found some code in this group but can't get my head around or
> change it enough to make it work for me.
>
> The file out looks like this: (cpuuse.out)
>
> Fri Dec 07 00:05:03 096  000  000  000      000    000  000  000
> 000   -001  000  000
> Fri Dec 07 00:06:04 096  000  000  000      000    000  000  000
> 000   -001  000  000
> Fri Dec 07 00:07:04 092  000  000  000      000    000  000  000
> 000   -001  000  000
> Fri Dec 07 00:08:04 097  000  000  000      000    000  000  000
> 000   -001  000  000
> Fri Dec 07 00:09:04 097  000  000  000      000    000  000  000
> 000   -001  000  000
> Fri Dec 07 00:10:04 096  000  000  000      000    000  000  000
> 000   -001  000  000
> Fri Dec 07 00:11:04 096  000  000  000      000    000  000  000
> 000   -001  000  000
> Fri Dec 07 00:12:04 098  000  000  000      000    000  000  000
> 000   -001  000  000
>
>
> I want to calculate the average of the numbers in column 5 (The ones
> in the 090's). Bare in mind there are more lines than this.
>
> The code I saw was:
>
> use strict;
> use warnings;
>
> my $file = $ARGV[0] || 'pickcpua.dat';
> my $col = $ARGV[1];
>
> open(my $CPUFILE, "<", $file) || die "Unable to open sorted file !";
>
> my @values;
> while (<$CPUFILE>) {
>   chomp;
>   my @col = split /,/;     # Assume basic comma delimited
>
> if ($col[$ARGV[1]] > 0)  {
>   push @values, $col[$ARGV[1]];   # Column 2 is what we want
>   }
>
> }
>
> my $total = 0;
> $total += $_ for @values;
> my $average = $total /@values;
>
> print "Average CPU Time for all servers in cpuatest.dat file is
> $average";
>
> All I need is an average figure of column 5.

I would write it something like this:

use strict;
use warnings;

my $file = $ARGV[ 0 ] || 'pickcpua.dat';

open my $CPUFILE, '<', $file or die "Unable to open '$file' $!";

my ( $total, $count );
while ( <$CPUFILE> ) {
    next unless /
        ^
        (?: Mon | Tue | Wed | Thu | Fri | Sat | Sun )
        \s+
        (?: Jan | Feb | Mar | Apr | May | Jun |
            Jul | Aug | Sep | Oct | Nov | Dec )
        \s+
        \d\d
        \s+
        \d\d : \d\d : \d\d
        \s+
        ( \d+ )
        /x;
    $total += $1;
    $count++;
    }

my $average = $total / $count;

print "Average CPU Time for all servers in $file file is $average\n";

__END__



John
-- 
use Perl;
program
fulfillment

-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
http://learn.perl.org/


Reply via email to