<=>, the spaceship operator, has an interesting property - when the two sides are equal, it returns 0. This is very useful, because then you say:

my $AoH = [ sort { $a->{under} <=> $b->{undef} || $a->{order} <=> $b->{order} } @$sqldata ];
This works because || evaluates it's left side, and if it's false (0 is false), it evaluates the right too. It returns the first true value it finds (or the last false one if it didn't).

Let's compare 2,2 and 2,1:

(2 <=> 2) == 0 so 0 || 2 <=> 1 evaluates to 2 <=> 1 (2 <=> 1) == 1 # the answer we wanted

BTW, I noticed you have 'sqldata'... This smells like you're doing fetching the entire result table as an array ref, and then sorting it... Why not make it into

select ... order by under, order;
This stuff is better (and probably more efficiently) handled on the server side.

Update: tphyahoo was right - but it was no typo... I wrote down $a twice when I should have written $b. Sorry!

-nuffin
zz zZ Z Z #!perl

In reply to Re: Sorting AoH by two keys by nothingmuch
in thread Sorting AoH by two keys by bradcathey

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.