Re: sorting a hash / 2008-06-01



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
.



Relevant Pages

  • Re: Hash order bug?
    ... a review of one's Data Structures course may be in order ... did I realize that the underlying data structure is a hash, ... If you need to iterate through a hash in order by key, ...
    (comp.lang.ruby)
  • Re: Parsing dhcpd.leases and squid access.log
    ... Paul Kraus wrote: ... Need to create a hash like data structure that contains the key as ... The dhcpd leases file contains all leases handed out and the ... - You never read from the %users hash. ...
    (perl.beginners)
  • Re: [rfc][patch] dynamic resizing dentry hash using RCU
    ... that to the dentry hash. ... the find details because it is not in code or pseudo code format. ... All you need it to know how to perform a lookup on both your old ... and new data structure, and the same algorithm is basically applicable ...
    (Linux-Kernel)
  • Re: hash table size
    ... You pointing out that a chess hash table is being done as a cache rather ... some sort of data structure that gets updated dynamically. ... simple and a fixed cost regardless of the size of the table. ...
    (rec.games.chess.computer)
  • Re: problem with hash & sort array
    ... Then I put the hash into an array with the sort ... The twist is I have to identify the duplicate ... a real data structure, and in the next place I make the exact opposite ...
    (comp.lang.perl.misc)