Create a second hash, with countries as the keys; the hash value for each country will be an anonymous array containing the cities belonging to that country:
#! perl
use strict;
use warnings;
my %h1 =
(
'Chicago, USA' => undef,
'Frankfurt, Germany' => undef,
'Berlin, Germany' => undef,
'Washington, USA' => undef,
'Helsinki, Finland' => undef,
'New York, USA' => undef,
);
my %h2;
for (keys %h1)
{
my ($city, $country) = split ', ';
push @{ $h2{$country} }, $city;
}
for (sort keys %h2)
{
print "$_: ", join(', ', sort { $a cmp $b } @{ $h2{$_} }), "\n";
}
Output:
16:29 >perl 819_SoPW.pl
Finland: Helsinki
Germany: Berlin, Frankfurt
USA: Chicago, New York, Washington
16:31 >
Note: Perl autovivifies the new $h2{$country} elements as needed.
Hope that helps,