Which produces the following output:use strict; use warnings; use feature qw /say/; my %hash = (a => 1, b => 2, c => 3, d => 2, e => 5, f => 3); my %HoA; for my $key (keys %hash) { my $value = $hash{$key}; push @{$HoA{$value}}, $key; } for my $key2 (keys %HoA) { my @keys = @{$HoA{$key2}}; say "Keys @keys have the same value: $key2 "; }
The formatting is not exactly what you wanted, but you have the basic algorithm and the results seem correct, I leave it to you to format the output according to your needs. Don't hesitate to ask if you have any further difficulty.$ perl reverse_hash.pl Keys a have the same value: 1 Keys c f have the same value: 3 Keys b d have the same value: 2 Keys e have the same value: 5
Just in case you need it for better understanding, this is what the HoA looks like at the end of the first loop populating it:
0 HASH(0x60025cbb8) 1 => ARRAY(0x60006f210) 0 'a' 2 => ARRAY(0x600462490) 0 'b' 1 'd' 3 => ARRAY(0x60048d1b8) 0 'c' 1 'f' 5 => ARRAY(0x600495808) 0 'e'
In reply to Re: compare text file and print occurrence of key and value
by Laurent_R
in thread compare text file and print occurrence of key and value
by waytoperl
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |