MY hash
Chicago, USA
Frankfurt, Germany
Berlin, Germany
Washington, USA
Helsinki, Finland
New York, USA
As someone else has already pointed out, this isn't a hash. It isn't even Perl. It's just a list of cities and their corresponding countries in English.
I suspect your hash is this:
(
'Chicago' => 'USA',
'Frankfurt' => 'Germany',
'Berlin' => 'Germany',
'Washington' => 'USA',
'Helsinki' => 'Finland',
'New York' => 'USA',
)
Did I guess right?
but i want i put like
Finland: Helsinki.
Germany: Berlin, Frankfurt.
USA: Chicago, New York, Washington.
Once again, this isn't anything in Perl. It's just an English language list of countries and corresponding lists of cities in those countries.
To me, the most natural Perl data structure to use to represent lists of cities by their corresponding countries is a hash of arrays.
(
'Finland' => [ 'Helsinki' ],
'Germany' => [ 'Berlin', 'Frankfurt' ],
'USA' => [ 'Chicago', 'New York', 'Washington' ],
)
So are you asking us how to create this second data structure (a hash of arrays) from the first data structure (a simple hash)?
use strict;
use warnings;
# Hash of countries by city
my %countries_by = (
'Chicago' => 'USA',
'Frankfurt' => 'Germany',
'Berlin' => 'Germany',
'Washington' => 'USA',
'Helsinki' => 'Finland',
'New York' => 'USA',
);
# Hash of arrays of cities by country
my %cities_by;
# Generate a hash of arrays of cities by country
# from a hash of countries by city...
while (my ($city, $country) = each %countries_by) {
push @{ $cities_by{$country} }, $city;
}
# Print a list of cities by country...
for my $country (sort keys %cities_by) {
for my $city (sort @{ $cities_by{$country} }) {
print "$country\t$city\n";
}
}
(This small example isn't Unicode-conformant.)
This Perl script prints…
Finland Helsinki
Germany Berlin
Germany Frankfurt
USA Chicago
USA New York
USA Washington
The other day in the Chatterbox, I recommended you take a beginning Perl course to learn the rudiments of the language. Have you enrolled in a course yet? If not, you should. (I can see you're in the Chatterbox right now asking how to perform simple text substitution in Perl using substr() instead of the substitution operator s///. This is more evidence that you really need to learn the fundamentals of the Perl programming language either from a good teacher or a good book. Trying to learn it by persistently asking poorly-articulated questions on PerlMonks is very unlikely to succeed.)
Jim
|