This code snippet can be used to serve the desired purpose
use strict
use warnings
my $filename = 'data.txt';
open(my $fh, '<', $filename) or die "Could not open file '$filename' $!";
my %count;
while (my $line = <$fh>) {
my @words = split(' ', $line);
my $ip = $words[0];
$count{$ip}++;
}
while (my ($k,$v)=each %count){
print "$k $v\n"
}
Explanation
- Open the file for reading
my $filename = 'data.txt';
open(my $fh, '<', $filename) or die "Could not open file '$filename' $!";
- Iterate over lines of file and find words by splitting the line on space. Extract the first column value from each line and store it in a hash, with the column as key and value as number of occurrence of key
my %count;
while (my $line = <$fh>) {
my @words = split(' ', $line);
my $ip = $words[0];
$count{$ip}++;
}
Note hash has following structure { "key" : "value" }
Here hash will contain the values as:
{
'10.10.10.1' => 2,
'10.10.10.3' => 1,
'10.10.10.4' => 1
}
- Finally iterate over key, value pairs in count hash and print the key i.e column and value i.e count
foreach my $key (sort { $count{$b} <=> $count{$a} } keys %count) {
print "$key $count{$key}\n"
}
- Here
sort { $count{$b} <=> $count{$a} } is for descending order sort on hash values
- Use
sort { $count{$a} <=> $count{$b} } for ascending order sort on hash values
- Use
sort { $a <=> $b } for ascending order sort on hash keys
- Use
sort {$b <=> $a} for descending order sort on hash keys