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

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.