Re: sorting a hash / 2008-06-01
- From: Gunnar Hjalmarsson <noreply@xxxxxxxxx>
- Date: Fri, 30 May 2008 15:11:22 +0200
dn.perl@xxxxxxxxx wrote:
I want to sort a hash. The hash contains a list of cities and their temperature
Well, I'd rather say it contains three hash references.
This is one sensible way to sort that data structure:
foreach my $state ( sort keys %hash ) {
print "State: $state\n";
foreach my $city ( sort { $a cmp $b } keys %{ $hash{$state} } ) {
print "$city = $hash{$state}{$city}{max_temp}\n";
}
print "\n";
}
and I want the 4 cities with max temp.
I'm not sure what you mean by that. Please clarify what's the desired output.
The problem is that the city-names are one extra level deep with the state-name coming in- between. I wondered whether I should build the hash differently.
Probably. This is one idea:
my %hash = (
'San Jose' => {
state => 'Calif',
max_temp => 84,
},
'San Fran' => {
state => 'Calif',
max_temp => 94,
},
);
my %hash = () ;---------------^^^^^^^^
$hash{Calif}{San Jose}{max_temp} = 84 ;
Hash keys with spaces need to be quoted.
$hash{Calif}{'San Jose'}{max_temp} = 84 ;
$hash{Calif}{San Fran}{max_temp} = 94 ;
$hash{Calif}{Cupertino}{max_temp} = 38 ;
$hash{Calif}{Fremont}{max_temp} = 66 ;
$hash{Texas}{Dallas}{max_temp} = 72 ;
$hash{Texas}{Austin}{max_temp} = 96 ;
$hash{Texas}{Fort Worth}{max_temp} = 62 ;
$hash{Mass}{Boston}{max_temp} = 96 ;
$hash{Mass}{Framingham}{max_temp} = 55 ;
$hash{Mass}{Worcester}{max_temp} = 55 ;
--
Gunnar Hjalmarsson
Email: http://www.gunnar.cc/cgi-bin/contact.pl
.
- Follow-Ups:
- Re: sorting a hash / 2008-06-01
- From: A. Sinan Unur
- Re: sorting a hash / 2008-06-01
- References:
- sorting a hash / 2008-06-01
- From: dn.perl@xxxxxxxxx
- sorting a hash / 2008-06-01
- Prev by Date: Re: Need help with a simple (I think) Perl script
- Next by Date: Re: Need help with a simple (I think) Perl script
- Previous by thread: Re: sorting a hash / 2008-06-01
- Next by thread: Re: sorting a hash / 2008-06-01
- Index(es):
Relevant Pages
|
|