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.
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.@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;
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
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |