I have written a script which processes data from $data variable and get the count of values of each key.
The script works fine but I am producing 2 hashes called %data_hash, %count_hash. One for storing the data and another to get the count of those key values.
#!/usr/bin/perl
use strict;
use warnings;
use Data::Dumper;
my $data = "KEY1,VAL1
KEY2,VAL1
KEY1,VAL2
KEY1,VAL3
KEY1,VAL4
KEY2,VAL2
KEY2,VAL3
KEY2,VAL4
KEY1,VAL5
";
my (%data_hash, %count_hash);
foreach my $each_data (split /\n/, $data){
my ($key, $val) = (split /,/, $each_data);
push( @{$data_hash{$key}}, $val );
}
print Dumper(\%data_hash);
foreach my $key (sort keys %data_hash) {
$count_hash{$key} = scalar @{$data_hash{$key}};
}
print Dumper(\%count_hash);
Can I have a single hash instead of 2 and get the count by retaining the data?