>> You can't sort a hash. Hashes are by definition unsorted. You can, however, display the contents of a hash in a sorted order <<

Erm what is the difference between sorting and displaying in a sorted order?

To my mind the phrase "sorting a hash" implies that the data in the hash is stored in a sored order (as it is in an array). That's never true. The order that the hash elements are stored in is defined by a hashing algorithm. That's where the name comes from.

In Reply To

Hashes do sort themselves.

Code

my %h = ( 5 => 'a', 3 => 'c', 4 => 'b' );

print %h;

You got lucky. Sometimes the hashing algorithm does seem to sort the array. But that can't be relied on. Try this:

Code

#! /usr/bin/perl -w

use strict;

my %h;

for (1 .. 20) { $h{$_} = 'x'; print %h, "\n"; }

Using Perl 5.6.1 on RedHat Linux 7.3, the hashing algorithm no longer gives a sorted hash once the key value goes beyond 9. But this behaviour is also dependent on Perl version and operating system.