ЭЛЕКТРОННАЯ БИБЛИОТЕКА КОАПП |
Сборники Художественной, Технической, Справочной, Английской, Нормативной, Исторической, и др. литературы. |
3.2.153 sortsort This function sorts the To do an ordinary numeric sort, say this: sub numerically { $a <=> $b; } @sortedbynumber = sort numerically 53,29,11,32,7; To sort in descending order, simply reverse the sub byage { $age{$a} <=> $age{$b}; } @sortedclass = sort byage @class; As an extension of that notion, you can cascade several different
comparisons using the handy comparison operators, which work nicely for
this because when they return sub prospects { $money{$b} <=> $money{$a} or $height{$b} <=> $height{$a} or $age{$a} <=> $age{$b} or $lastname{$a} cmp $lastname{$b} or $a cmp $b; } @sortedclass = sort prospects @class; To sort fields without regard to case, say: @sorted = sort { lc($a) cmp lc($b) } @unsorted; And finally, note the equivalence of the two ways to sort in reverse: sub backwards { $b cmp $a; } @harry = qw(dog cat x Cain Abel); @george = qw(gone chased yz Punished Axed); print sort @harry; # prints AbelCaincatdogx print sort backwards @harry; # prints xdogcatCainAbel print reverse sort @harry; # prints xdogcatCainAbel print sort @george, "to", @harry; # Remember, it's one LIST. # prints AbelAxedCainPunishedcatchaseddoggonetoxyz Do not declare $a and $b as lexical
variables (with my). They are package
globals (though they're exempt from the usual restrictions on globals when
you're using One last caveat. Perl's sort is implemented in terms of C's qsort(3) function. Some qsort(3) versions will dump core if your sort subroutine provides inconsistent ordering of values. |