The canonical tool for sorting by a temporary (and possibly expensive to calculate) key is the Schwartzian Transform (See answers to When does it pay to use the schwartzian transform? and What is "Schwarzian Transform" (aka Schwartzian) or Super Search it yourself).

The guts of the technique is to use map to generate a temporary array containing the original (unsorted) data and a key string. Use sort to sort the array by the key string, and another map to translate the sorted array back into the original (but now sorted) form.

The code looks something like this:

use strict; use warnings; my @array = qw(one4wobble two3wibble three2wig four1wog); @array = map {$_->[1]} # Convert back to original form sort {$a->[0] <=> $b->[0]} # Sort on the generated key map {[(/(\d+)/ ? $1 : -1), $_]} # Generate [key, data] pairs @array; print "@array";

Prints:

four1wog three2wig two3wibble one4wobble

Perl is environmentally friendly - it saves trees

In reply to Re: sort array by part of the string by GrandFather
in thread sort array by part of the string by vitaly

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.