Sort isn't acting like I expect it to and I'm a little confused. I have a hash reference that looks like this:
$sort_line_contents->{element_one}->{element_two}

I want to reverse sort on element_one (numerically) and then sort normally on element_two. Here is an example of my data set:

$sort_line_contents->{1}->{2} = Item1; $sort_line_contents->{0}->{3} = Item2; $sort_line_contents->{1}->{4} = Item3; $sort_line_contents->{1}->{5} = Item4; $sort_line_contents->{2}->{6} = Item5;

I want to take that information and force it into an order like this:
Item5
Item1
Item3
Item4
Item2

My first crack at this was using a sort statement like so:

my @hash_keys2 = sort { %{$sort_line_contents}->{$b} <=> %{$sort_li +ne_contents}->{$a} } keys %{$sort_line_contents};

But this gives me an incorrect order. Instead of giving me an order like this: 2, 1, 1, 1, 0 it gives me something like 0, 2, 1, 1, 1. I could not get this straightened out, so eventually ended up substituting this line:
foreach (reverse sort keys %{$sort_line_contents}) { push(@hash_keys2, +$_);}
I'm even more confused because the second sort using the second value works AS EXPECTED:
foreach my $hk (@hash_keys2){ my @filli = sort { $sort_line_contents->{$hk}->{$a} <=> $sort_li +ne_contents->{$hk}->{$b} } keys %{$sort_line_contents->{$hk}}; foreach (@filli){ #output to other part of program } }
My question is, why doesn't the sort on the hash ref give me the expected behaviour? Is there a problem with the way I am expanding my $sort_line_contents reference? I see that it is reading out the correct VALUES, it is just putting them in an unexpected order. I get the same unexpected order with the <=> and the cmp operators???

oakbox


In reply to Sort not acting as expected on Hash Ref by oakbox

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.