When you want to sort a list, other than by a straight lexical or numerical comparision of its elements, the classic approach is the Schawatzian Transform.
# UNTESTED # after opening files @tosort = <TOSORT>; chomp @tosort; @sorted = map { $_->[1] } sort { $a->[0] cmp $b->[0] } map { [ (split('|', $_))[1] , $_ ] } @tosort; for (@sorted) { print SORTED "$_\n" }

The map {} sort {} map {} is read from the bottom up.

The bottom map creates a list of array references, one arrayref per element of @tosort. each arrayref has as it's first element the phone number portion of the element, and as its second element the original element of tosort. The return value of map is a list of these arrayrefs that is fed to the sort.

The sort then sorts these arrayrefs based on comparsion of the first element of each, which is the phone number. The return value of the sort is a list of the now-sorted arrayrefs, which is fed to the top map.

The top map then picks the original values of @tosort out of the arrayrefs. The return value of this map is a list that is put into @sorted.

The Schwarzian transform does the needed sort, with the added advantage that, if the sort criteria is some expensive operation (in this case it was just the split), it is only oden once per element, whereas if it were in the sort, it would be done many more times.

The Schwartzian Transform is named for merlyn, who also goes by the name of Randal Schwartz.

--Bob Niederman, http://bob-n.com


In reply to Re: sorting arrays... by bobn
in thread sorting arrays... by iamrobj

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.