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:
Make top X

 



mmcw
User

Apr 17, 2001, 7:04 AM

Post #1 of 2 (84 views)
Make top X Can't Post

I have a log file called search.log.

This is a little flat database file.
Something like this:

test|12-04-2001|112.111.111.111
1001|12-04-2001|112.111.111.111
2332|13-04-2001|112.111.111.111
test|14-04-2001|112.111.111.111
2332|13-04-2001|112.111.111.111
1001|15-04-2001|112.111.111.111
test|16-04-2001|112.111.111.111
2222|15-04-2001|112.111.111.111

What I now want is to have a top X from the the first colom (test,1001 2332 etc.)

forexample:

TOP 3
1: test (3)
2: 1001 (2)
3: 2332 (2)



rGeoffrey
User / Moderator

Apr 18, 2001, 2:13 PM

Post #2 of 2 (76 views)
Re: Make top X [In reply to] Can't Post

Here is an option...


Code
#!/usr/local/bin/perl 

use strict;

#open (DATA, 'datafile.log') or die "could not open log file $!";
#my @lines = <DATA>;
#close DATA;

my $log_file_test = <<EOF;
test|12-04-2001|112.111.111.111
1001|12-04-2001|112.111.111.111
2332|13-04-2001|112.111.111.111
test|14-04-2001|112.111.111.111
2332|13-04-2001|112.111.111.111
1001|15-04-2001|112.111.111.111
test|16-04-2001|112.111.111.111
2222|15-04-2001|112.111.111.111
EOF

my @lines = split ("\n", $log_file_test);

my %Counted_Hash;
my $top_wanted = 3;

foreach my $line (@lines) {
my $id = (split ('\|', $line))[0];
$Counted_Hash{$id}++;
}

my $ct = 0;
foreach (reverse sort { $Counted_Hash{$a} <=> $Counted_Hash{$b} } keys (%Counted_Hash)) {
print "$_ ($Counted_Hash{$_})\n";
$ct++;
last if ($ct == $top_wanted);
}

The trick is to make a big hash of all the first fields and then sort them by how many times they were used. Using $ct and $top_wanted we can quit early from the printing loop.

--
Sun Sep 9, 2001 - 1:46:40 GMT, a very special second in the epoch. How will you celebrate?

 
 


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

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