my @newarray = map { $_->[0] }
               sort { $a->[1] <=> $b->[1] }
               map { $_ => n_primes_less_than_25th_power($_) }
             @oldarray;

The essence is that each element of @oldarray is passed to the map which does the complex calculation on that element and creates a 2-element array containing the original element and the calculated value. Those are passed to the sort ...

There's a big problem here. The first map expression must return a reference to a two-element array to pass to sort:
    map { [ $_ => n_primes_less_than_25th_power($_) ] }

Note that the the  => (fat comma) in the above expression is just an idiosyncratic variation on the more common  , (comma) operator, so another version of the expression might be:
    map [ $_, n_primes_less_than_25th_power($_) ],
(which also dispenses with the enclosing  { ... } code block (update: because  [ ... ] is a simple expression); note this needs a terminating comma operator).

One way to easily control sort order is to realize that the  <=> and  cmp operators (see perlop) return (-1, 0, 1) as the result of their comparisons. If you have a scalar  $order that may have only the values 1 (ascending) or -1 (descending), it's easy to control ordering:
    sort { $order * ($a->[1] <=> $b->[1]) }
(among other ways, of course).

For tutorials on sorting and transformation sorts, see List Processing, Filtering, and Sorting, and in particular Understanding transformation sorts (ST, GRT), the details. See also A Fresh Look at Efficient Perl Sorting for an in-depth discussion of ST and GRT sorting.


Give a man a fish:  <%-(-(-(-<


In reply to Re^7: Sorting based on any column by AnomalousMonk
in thread Sorting based on any column by Anonymous Monk

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.