What decides the order of keys when I print a Perl hash?

Elements of a hash are printed out in their internal order, which can not be relied upon and will change as elements are added and removed. If you need all of the elements of a hash in some sort of order, sort the keys, and use that list to index the hash.

If you are looking for a structure that holds its elements in order, either use an array, or use one of the ordered hash’s on CPAN.

the only ordering you can rely upon from a list context hash expansion is that key => value pairs will be together.

Leave a Comment