sort and How do I sort an array by (anything)?

Here's one way to do it with fairly complex sort criteria and a Schwartzian transform (assuming I've understood the requirements correctly):

#!/usr/bin/env perl use warnings; use strict; use List::Util 'shuffle'; use Test::More tests=>1; my @expect = qw/ frooc froof froz ebaz eyun ebxu quz qun que /; my @input = shuffle @expect; sub special { # sort routine used below $$a[1] <=> $$b[1] # first sort by categories or # then sort by the desired condition per category $$a[1]==1 ? $$a[0] cmp $$b[0] # category 1 (/r/) : ( $$a[1]==2 ? $$a[2] cmp $$b[2] # category 2 (/^e/) : $$b[3] cmp $$a[3] ) # category 3 (rest) } my @output = # sort with Schwartzian transform # Step 3: get back the orig_str out of the array map { $$_[0] } # Step 2: sort with the "special" function defined above sort special # Step 1: each item -> [orig_str, category, third_chr, last_chr] # where category is: /r/ => 1, /^e/ => 2, rest => 3 map { [$_, /r/?1:(/^e/?2:3), substr($_,2,1), substr($_,-1,1)] } @input; is_deeply \@output, \@expect or diag explain \@output;

In reply to Re: How to perform different sorts on multiple sections of items in the same array by Anonymous Monk
in thread How to perform different sorts on multiple sections of items in the same array by estreb

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.