The surname() function (something you have to write) just extracts the surname from a line. One straight-forward solution is:@sorted = sort { surname($a) cmp surname($b) } @lines;
I.e. split the line on vertical bars, get the full name, split the full name on spaces and return the second element.sub surname { my $line = shift; my @fields = split(/\|/, $line); my $fullname = $fields[1]; # extract full name my ($first, $last) = split(/ /, $fullname); return $last; }
There are more clever and efficient ways to write the surname() function, but I just want to demonstrate that you don't have to try to be clever to solve the problem.
This approach extends to any sorting by any property. Just write a function to extract (or compute) that property from the things you are sorting.
If you are concerned about efficiency, have a look at this write-up: A Fresh Look at Efficient Perl Sorting where topics such as the Orcish Maneuver, Schwartzian Transform, and packed-default sort are discussed.
In reply to Re: custom sorting
by pc88mxer
in thread custom sorting
by Anonymous Monk
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |