use strict; use IO::File; use Time::Piece; main(); sub main { unless (@ARGV) { die "No argments : specify file name of log."; } my $filename = $ARGV[0]; my $fp = IO::File->new($filename, 'r') or die "Failed to open log file : [$filename]"; # read a line. # print_line($fp); # print number of lines; # print count_lines($fp); # print IP address of first line. # my $line = $fp->getline; # print extract_ip_address($line); # print_ip_count($fp); # print time stamp # my $line = $fp->getline; # print extract_time_stamp($line); # print date count print_day_count($fp); $fp->close; } # print a line of file; sub print_line { my ($fp) = @_; # or my $fp = shift; # or my $fp = $_[0]; print $fp->getline; } # count lines sub count_lines { my ($fp) = @_; my $count = 0; my $line; while ($line = $fp->getline) { $count++ } $count; } # extract IP address from log line. sub extract_ip_address { my ($line) = @_; my ($ip_address) = $line =~ m/^(\d+\.\d+\.\d+\.\d+)/; $ip_address; } # print number of lines each with IP addresses. sub print_ip_count { my ($fp) = @_; my %ip_count; while (my $line = $fp->getline) { my $ip_address = extract_ip_address($line); next unless $ip_address; $ip_count{$ip_address}++; } # print each records. my @sorted_keys = sort { $ip_count{$b} <=> $ip_count{$a} } keys %ip_count; for my $key (@sorted_keys) { #print "$key $ip_count{$key}\n"; printf("%15s %10d\n", $key, $ip_count{$key}); } # for my $key (keys %ip_count) { # #print "$key $ip_count{$key}\n"; # printf("%15s %10d\n", $key, $ip_count{$key}); # } # total number of ip addresses. my $number_of_ip = keys %ip_count; print "number of IP addresses: $number_of_ip"; } # print access count of each days. sub print_day_count { my ($fp) = @_; my %day_count; while (my $line = $fp->getline) { my $timestamp = extract_time_stamp($line); next unless $timestamp; my $ts_str = $timestamp->strftime("%y/%m/%d"); $day_count{$ts_str}++; } # print each records. my @sorted_keys = sort(keys %day_count); for my $key (@sorted_keys) { #print "$key $ip_count{$key}\n"; printf("%15s %10d\n", $key, $day_count{$key}); } } # extract time stamp sub extract_time_stamp { my ($line) = @_; my ($timestamp) = $line =~ m/\[(.+?)\]/; unless ($timestamp) { return undef; } # parse timestamp such as '09/Mar/2004:22:04:29 -0500' Time::Piece->strptime($timestamp, "%d/%b/%Y:%H:%M:%S %z"); }