If you want to compare by more than one field, this is done like this:
(extra line feeds added to prevent word wrap on the Monk page which is shorter than my standard 80 chars).

The sort{} function can even be a separate subroutine rather than the anonymous one shown here. The main point is that the "less than, equal, greater than" value is the final return statement of this anon sub and "tie breaker" is implemented as a series of logical statements. Zero (equal) is false and if that is the case, then the logical statement keeps evaluating until it runs out of "tie breaker" stuff or reaches a conclusion.

@input_lines = sort {my ($a_name_last,$a_name_first,$a_city ) = split(/\s+/,$a); my ($b_name_last,$b_name_first,$b_city) = split(/\s+/,$b); $a_name_last cmp $b_name_last or $a_name_first cmp $b_name_first or $a_city cmp $b_city }@input_lines;
Note is is possible to intermix "cmp" compares (alpha) with the "spaceship" operator <=> which is numeric only. The "standard" ways that these comparison functions work is returning (+1,0,-1) although in Perl it could be that positive value, 0, negative value works? I would stick with just +1,0,-1 if you write your own wild comparison function. I mean you can literally make a compare function where B sorts before A if you want to do that.

Update: If the context of what is being compared is known, I strongly recommend putting that application context into the code. Like above "Smith Bob Chicago" will come before "Smith Bob Houston" and is easy to see and understand.


In reply to Re^6: Emulating 'sort' command through a Perl by Marshall
in thread Emulating 'sort' command through a Perl by paragkalra

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.