Link to home
Start Free TrialLog in
Avatar of uluttrell
uluttrell

asked on

IP Counter

This is not a homework assignment.
I need to record any IPs that appear more thn 50 times in a file.  Once the IP appears more than 50 times in a file, I need to copy that IP address to a new file.

How is this done in perl?
Avatar of ultimatemike
ultimatemike


You can just create a hash, with the key as an IP. Each time that you encounter an IP, increase the value of that IP in the hash by 1.  Something like this should work - it's not tested, but it should at least give you an idea.

my %ips;


while (<>) {
     #code to read in IP
     $ips{$currentip}++;
}


foreach ( keys($ips) ) {
     print if ($ips{$_} > 0);

well, to make the code more complete (and confusing :-) ):

while(<>)
{
  print "$1\n" if(/((?:\d+\.){3}\d+)/ && ++$ips{$1} > 50);
}

The above will give you ip address reading, counting, and printing.
ASKER CERTIFIED SOLUTION
Avatar of inq123
inq123

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of FishMonger
while (<>) {
   ++$ip{$1} if (/((\d{1,3}\.){3}\d{1,3})/g);
}

open OUT, ">redundant_ip" or die "could not open reduntant_ip file <$!>";
foreach $ip (sort keys %ip) {
   print $ip if ($ip{$ip} > 50);
}
close OUT;
I forgot to include the FH and the \n on the print statement, so it should read:
   print OUT "$ip\n" if ($ip{$ip} > 50);
Avatar of uluttrell

ASKER

inq123,
Your code is best suited for what I need.  I am awarding the points to you.
Thanks!