It is often repeated that hashes in Perl do not preserve insertion order. Yet:
#!/usr/bin/perl use strict; use warnings; use feature qw/say/; my %hoh = ( foo => { value => 'first' }, bar => { value => 'second' }, baz => { value => 'third' }, ); for my $elem (sort values %hoh) { say "value => " . $elem->{value}; }
Output:
value => first value => second value => third
What actually happens is that sort uses the stringified value, in effect the memory address, of the references for comparison, and the addresses of the hashrefs in the toplevel hash tend to (strictly) monotonously increase in the order the interpreter encounters them, i.e. in insertion order.
Obviously, this is not 100% reliable, and only works as is if the elements are references themselves. For scalars some nastiness with 'unpack "p"' or similar would be needed.
Still, it is sort of neat and it was surprising when I've first encountered it.
Edit and clarification: I'm not saying that you should ever use this (in fact, I'm saying that you shouldn't, the comments below describe why). It looks like as if it really preserved insertion order, but actually the trick relies on implementation details (memory allocation) you can't (or shouldn't want to) control.
|
|---|