Recently I had to sort some records based on the values of 2 different fields, for example, given

X 4143 61 Y 51 1325 Z 543 1543
I wanted them sorted this way:
Y 51 1325 X 4143 61 Z 543 1543

Because 51 is lower than 61, and the latter lower than 543

Surely this is nothing new, but I found the solution quite instructive, so I decided to share it here

It uses Schwartzian transformation. An explanation could be found here

Comments are welcome

citromatik

use strict; use warnings; use Data::Dumper; my @sorted = map {pop @$_ } sort { $a->[0] <=> $b->[0] || $a->[1] <=> $b->[1] } map { [ (sort { $a <=> $b } @$_[1,2]),$_ ] } map { [split /\s+/] } <DATA>; print Dumper \@sorted; __DATA__ A 15134 135 B 413 6161 C 33 16199 D 16141345 135

In reply to Sorting on 2 fields with the same priority by citromatik

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.