CGI/Perl Guide | Learning Center | Forums | Advertise | Login
Site Search: in

  Main Index MAIN
INDEX
Search Posts SEARCH
POSTS
Who's Online WHO'S
ONLINE
Log in LOG
IN

Home: Perl Programming Help: Intermediate: Re: [jeffersno1] script to count per hour success/error from logs: Edit Log



FishMonger
Veteran / Moderator

Nov 13, 2012, 8:36 AM


Views: 3978
Re: [jeffersno1] script to count per hour success/error from logs

Use the warnings pragma instead of the -w switch.

ALWAYS use the strict pragma and declare your vars, which is done with the 'my' keyword.

Var names should give describe what kind of data they hold. Some or most of your vars fails to do so.

Use a lexical var for the filehandle instead of the bareword and use the 3 arg form of open and the die statement should include the reason it failed.

It's more efficient to use a while loop instead of the for loop, when looping over the file.

When you split the csv line, only extract/save the needed fields and drop the rest.

You should build up a HoHoH (Hash of Hashes of Hashes) that holds the data.


Code
#!/usr/bin/perl 

use strict;
use warnings;

my $logfile = 'data.log';
open my $log_fh, '<', $logfile or die "failed to open '$logfile' $!";

my %booking_stats;
while (my $line = <$log_fh>) {

chomp $line;
my ($datestamp, $booking, $pass_name, $status) = (split(/,/, $line))[0,1,5,7];
next if $booking ne 'BOOK';

my ($date) = $datestamp =~ /^([^:]+)/;
if ($status eq 'success') {
$booking_stats{"$date:00:00"}{$pass_name}{success}++;
}
else {
$booking_stats{"$date:00:00"}{$pass_name}{fail}++;
}
}
close log_fh;

print "Time,Pass Name,Success,Failures\n";

foreach my $date ( sort keys %booking_stats ) {
foreach my $name ( sort keys %{$booking_stats{$date}} ) {
$booking_stats{$date}{$name}{success} //= 0;
$booking_stats{$date}{$name}{fail} //= 0;

printf("%s,%s,%d,%d\n", $date,
$name,
$booking_stats{$date}{$name}{success},
$booking_stats{$date}{$name}{fail}
);
}
}



(This post was edited by FishMonger on Nov 13, 2012, 8:36 AM)


Edit Log:
Post edited by FishMonger (Veteran) on Nov 13, 2012, 8:36 AM


Search for (options) Powered by Gossamer Forum v.1.2.0

Web Applications & Managed Hosting Powered by Gossamer Threads
Visit our Mailing List Archives