I have written the following code to read a file, slurp, identify IP addresses and track the number of occurrences of each address using a hash structure. The problem is that instead of my key being the IP address matched from regex, the key is the entire line on which the IP address appears. How do I fix this? (I believe the issue has to do with the fact that slurping is done line by line)
%ipcount;
@fileslurp = <FH>;
foreach(@fileslurp){
if($_ =~ m/(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})/){
$ipcount{$_}++;
}
}
$numIP = scalar keys %ipcount;
print "Number of unique IP: $numIP \n";
foreach $ipaddress (sort { $ipcount{b} <=> $ipcount{a} } keys %ipcount){
print "$ipaddress: $ipcount{$ipaddress} \n";
}
Looks like you are already doing a group match, just change $_ to $1 when adding to the hash.
%ipcount;
@fileslurp = <FH>;
foreach(@fileslurp){
if($_ =~ m/(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})/){
$ipcount{$1}++;
}
}
$numIP = scalar keys %ipcount;
print "Number of unique IP: $numIP \n";
foreach $ipaddress (sort keys %ipcount){
print "$ipaddress: $ipcount{$ipaddress} \n";
}
Get in the habit of using use strict;
and use warnings;
in EVERY perl script. It will help you catch problems.