I have a space delimited text file I am reading and am trying to add up data based on month, the data looks like this:
Mon Apr 04 08:00:00 MDT 2011 120.72 0.3 0.707 25.609 25.609
Mon Apr 04 07:45:00 MDT 2011 119.94 0.3 0.707 25.443 25.443
I’m trying to just add up monthly totals:
#!/usr/bin/perl
use strict;
use warnings;
use diagnostics;
use vars;
my $line;
my @data;
my @months;
my ($day, $month, $date, $time, $gmt, $year, $volt, $amp, $pf, $watt, $voltamp,
$voltsum, $wattsum, $count, $months, $monthlytotal );
$voltsum = 0;
$wattsum = 0;
open(DATAFILE, "@ARGV") || die $!;
@months = qw( Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec );
while (<DATAFILE>) {
$line = $_;
chomp $line;
@data = split(/\s/,$line);
$day = $data[0];
$month = $data[1];
$date = $data[2];
$time = $data[3];
$gmt = $data[4];
$year = $data[5];
$volt = $data[6];
$amp = $data[7];
$pf = $data[8];
$watt = $data[9];
$voltamp = $data[10];
I want to match the month, add my data up, and print the result once, but my flow control is wrong, any idea on how to do this correctly?
I want read each line, test which month it is, add all similar months together, and return the result.
foreach $months(@months) {
if ( $months =~ $month ) {
$voltsum += $voltamp;
$wattsum += $watt;
print "$month $year $wattsum $voltsum\n";
}
elsif ( $months !~ $month ) {
$voltsum = 0;
$wattsum = 0;
}
}
}
close (DATAFILE);
# print "Month Year Watts Vars\n" ;
# print "--------------------------\n";
# print " $months $month $year $wattsum $voltsum\n\n";
You might benefit from using a module to parse your timestamp. However, a simple fix might be to do something like this:
Not exactly waterproof, but it might suit your needs. Then you can simply extract the month data with