Документация

Table of Contents |

## 9.2. Sorting with IndicesIn the same way we used indices to solve a few problems with my @sorted = sort qw(Gilligan Skipper Professor Ginger Mary_Ann); print "@sorted\n"; which necessarily results in: Gilligan Ginger Mary_Ann Professor Skipper But what if we wanted to look at the original list and determine which element of the original list now appears as the first, second, third, and so on, element of the sorted list? For example, Ginger is the second element of the sorted list and was the fourth element of the original list. How do we determine that the second element of the final list was the fourth element of the original list? Well, we can apply a bit of indirection. Let's not sort the actual names but rather the indices of each name: my @input = qw(Gilligan Skipper Professor Ginger Mary_Ann); my @sorted_positions = sort { $input[$a] cmp $input[$b] } 0..$#input; print "@sorted_positions\n"; This time, Actually, we have the inverse of the rank. We still don't know, for a given name in the original list, which position it occupies in the output list. But with a bit more magic, we can get there as well: my @input = qw(Gilligan Skipper Professor Ginger Mary_Ann); my @sorted_positions = sort { $input[$a] cmp $input[$b] } 0..$#input; my @ranks; @ranks[@sorted_positions] = (0..$#sorted_positions); print "@ranks\n"; The code prints my @input = qw(Gilligan Skipper Professor Ginger Mary_Ann); my @sorted_positions = sort { $input[$a] cmp $input[$b] } 0..$#input; my @ranks; @ranks[@sorted_positions] = (1..@sorted_positions); for (0..$#ranks) { print "$input[$_] sorts into position $ranks[$_]\n"; } This results in: Gilligan sorts into position 1 Skipper sorts into position 5 Professor sorts into position 4 Ginger sorts into position 2 Mary_Ann sorts into position 3 This general technique can be convenient if we need to look at our data in more than one way. Perhaps we keep many records in order by a numeric code for efficiency reasons, but we occasionally want to view them in alphabetical order as well. Or maybe the data items themselves are impractical to sort, such as a month's worth of server logs. |

Table of Contents |