We don't bite newbies here... much | |
PerlMonks |
Hashes do preserve insertion order after allby kikuchiyo (Hermit) |
on Jul 31, 2019 at 16:00 UTC ( [id://11103651]=perlmeditation: print w/replies, xml ) | Need Help?? |
It is often repeated that hashes in Perl do not preserve insertion order. Yet:
Output:
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.
Back to
Meditations
|
|