August 1999 | Return to the Perl Hardware Store | Slide #5 |
@fruit = qw(Durian Cherry Apple Eggplant Banana); @indices = sort {$fruit[$a] cmp $fruit[$b] } (0 .. $#fruit);
@indices is 2, 4, 1, 0, 3.
The alphabetically first item is #2; alphabetically second is #4, etc.
Do the same thing again
@ranks = sort {$indices[$a] <=> $indices[$b]} (0 .. $#fruit);
@ranks is 3, 2, 0, 4, 1
The Durian is third, the Cherry is second, the Apple is 0th.
@ordinal = qw(first second third fourth fifth); for ($i=0; $i<@fruit; $i++) { print "The $fruit[$i] will come $ordinal[$ranks[$i]]\n"; } # ``The Durian will come fourth.'' # ``The Cherry will come third.''
@ranks has the opposite meaning of @indices
I borrowed this from the APL folks
Those APL folks are twisted. Stay away from them.
Next | Copyright © 1999 M-J. Dominus |