Well, since you said "efficient", I'll offer my favorite:

@origarray= @origarray[ do { my @by= map {(split(/\|/,$_,3))[2]} @origarray; sort {$by[$a] cmp $by[$b]} 0..$#origarray } ];
The above should be about as fast as you can get (though none of that matters unless you are sorting a huge number of items).

The "obvious" other two choices involve repeatedly extracting the substring to be compared (can be much slower but requires the least amount of memory), or using the Schwartzian Transform which does something similar to my method except it makes a ton of very small arrays w/o names instead of one array with a name (falls between the other two methods in speed but requires the most memory).

Update 2: Thanks to arhuman for reminding me of "my other favorite sorting scheme". His method is harder for me to compare. I suspect it may be faster and require only slightly more memory than mine above, at least for some cases. In any case, it is at least close.

I tend to use it when sorting on multiple fields, especially if they constitute most of the data. I use my method above to simultaneously sort multiple related lists (since none of the other methods can do that) -- though you have to save the list returned by sort to do that.

Updated to add missing ')'.

        - tye (but my friends call me "Tye")

In reply to (tye)Re: Substring Sort by tye
in thread Substring Sort 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.