This works in that the final "foreach" returns the fields in the order of the "Position" value
If you run this code multiple times, it should show that the ordering changes (because hash ordering is random), so you'll see it is actually not working - you probably just saw them in order by chance, or because you're on an older version of Perl where hash ordering was less random. If you turn on warnings, you'll see several "Use of uninitialized value in numeric comparison (<=>)" warnings, hinting that something is wrong (always Use strict and warnings!). And if you use Data::Dumper to look at the data structure after the sort, you'll see a new 'Position' => {} element in the data structure, which explains why the code did not crash: Perl autovivified a hash reference for you when you tried to access the nonexistent hash.
How does the hash of hashes find the "Position" value when the "fieldname" level has been skipped?
Note you're not actually skipping them - keys %{$fields{$table}} returns the keys such as ("Field_2", "Field_1", "Field_3"). This means that in your sort, that's what $a and $b will be. And now, if you look at your sort function and compare it to the data structure, perhaps you can see what's wrong: Change $fields{$table}{'Position'}{$a} to $fields{$table}{$a}{'Position'} (and the same for $b) and your code works fine :-) swl's tips for shortening the code a bit are useful, too. (See also the Basic debugging checklist.)
In reply to Re: Sorting a hash by a well buried key
by haukex
in thread Sorting a hash by a well buried key
by lb483
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |