in reply to Re^5: Emulating 'sort' command through a Perl
in thread Emulating 'sort' command through a Perl

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.