in reply to Hash in Perl
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, |
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: Hash in Perl
by rammohan (Acolyte) on Jan 02, 2014 at 06:41 UTC | |
by Athanasius (Archbishop) on Jan 02, 2014 at 06:53 UTC | |
by rammohan (Acolyte) on Jan 02, 2014 at 06:59 UTC | |
by Anonymous Monk on Jan 02, 2014 at 07:17 UTC |