Re: sorting a hash / 2008-06-01
- From: "John W. Krahn" <someone@xxxxxxxxxxx>
- Date: Fri, 30 May 2008 12:49:12 GMT
dn.perl@xxxxxxxxx wrote:
I want to sort a hash. The hash contains a list of cities and their
temperature and I want the 4 cities with max temp. 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. A
different format would be: state_city, with the underbar separating
the state and the city.
$hash{Calif_Cupertino}{max_temp} = 38 ;
instead of
$hash{Calif}{Cupertino}{max_temp} = 38 ;
my %hash = () ;
$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 ;
How do I sort this hash, please?
$ perl -le'
my %hash = (
Calif => {
"San Jose" => { max_temp => 84 },
"San Fran" => { max_temp => 94 },
Cupertino => { max_temp => 38 },
Fremont => { max_temp => 66 },
},
Texas => {
Dallas => { max_temp => 72 },
Austin => { max_temp => 96 },
"Fort Worth" => { max_temp => 62 },
},
Mass => {
Boston => { max_temp => 96 },
Framingham => { max_temp => 55 },
Worcester => { max_temp => 55 },
},
);
print "City: $_->[0] Temperature: $_->[1]"
for (
sort { $b->[ 1 ] <=> $a->[ 1 ] }
map { my $hash = $_; map [ $_, $hash->{ $_ }{ max_temp } ], keys %$hash }
values %hash
)[ 0 .. 3 ];
'
City: Austin Temperature: 96
City: Boston Temperature: 96
City: San Fran Temperature: 94
City: San Jose Temperature: 84
John
--
Perl isn't a toolbox, but a small machine shop where you
can special-order certain sorts of tools at low cost and
in short order. -- Larry Wall
.
- 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: sorting a hash / 2008-06-01
- Previous by thread: sorting a hash / 2008-06-01
- Next by thread: Re: sorting a hash / 2008-06-01
- Index(es):
Relevant Pages
|
|