cipher has asked for the wisdom of the Perl Monks concerning the following question:
I want to find the top unique ip's with their count from this array. Example: Output should be top n, In this case n = 2.@ip = (1.1.1.1 2.2.2.2 1.1.1.1 4.4.4.4 1.1.1.1 4.4.4.4)
I have read many forums and posts and I see most perl experts recommend using hash for this purpose. I already have a running code but here I have my IP address in a scalar, My new code is different and has IP address in an array. Here is my running code:IP -- Count 1.1.1.1 3 4.4.4.4 2
I want to acheive similar output but from array. Example:use strict; use warnings; my $fields = (); my @logs = (); my $reg_sip = (); my $si = (); my $sIp = (); my $key = (); my %sIp = (); open FILE, "c:/perl/fw.log" or die $!; while ($fields = <FILE>) { @logs = split (/ /,$fields); foreach $reg_sip (@logs) {if ($reg_sip =~ m/src=\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1 +,3}/) {$si = substr $reg_sip, 4; $sIp{$si} += 1; }} } my $top = 10; print "\nTop Ten Sources are\n"; my $i =0; foreach $key (sort {$sIp{$b} <=> $sIp{$a}} keys %sIp) {print "\n$key\t - $sIp{$key}"; $i++; if ($i == $top){last;}} ## Result Top Ten Sources are 10.71.74.100 - 2706 192.168.237.103 - 1896 192.168.237.119 - 1473 10.71.74.73 - 1302 192.168.237.110 - 650 10.71.74.139 - 325 10.71.74.74 - 238 192.168.33.32 - 213 192.168.237.247 - 124 192.168.237.250 - 18
use strict; use warnings; my @srcs = (); open FILE, "c:/perl/fw.log" or die $!; while (<FILE>) { if (my ($src) =/\bsrc=(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})/){push +@srcs, $src;} } #### Code to print Top n unique ip's in descending order from @srcs.
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Top n Unique count from Array
by davido (Cardinal) on Mar 25, 2011 at 08:20 UTC | |
by cipher (Acolyte) on Mar 25, 2011 at 08:25 UTC | |
|
Re: Top n Unique count from Array
by JavaFan (Canon) on Mar 25, 2011 at 10:13 UTC | |
|
Re: Top n Unique count from Array
by Anonymous Monk on Mar 25, 2011 at 07:36 UTC | |
by cipher (Acolyte) on Mar 25, 2011 at 07:52 UTC | |
by Anonymous Monk on Mar 25, 2011 at 09:15 UTC | |
by cipher (Acolyte) on Mar 25, 2011 at 10:26 UTC | |
by Anonymous Monk on Mar 25, 2011 at 11:36 UTC | |
|