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,
| Athanasius <°(((>< contra mundum | Iustus alius egestas vitae, eros Piratica, |
In reply to Re: Hash in Perl
by Athanasius
in thread Hash in Perl
by rammohan
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |