Want to sort a complex data structure by some element efficiently?
For example, how do you sort an array of strings by their length?
Use the transform:
@sorted = map { $_->[1] } sort { $a->[0] <=> $b->[0] } map { [ length $_, $_ ] } @strings;
Confused? Put in temporary arrays, just to see what we're doing.

create a temporary array of anonymous arrays
(0: length of the string, 1: the string)

@temp = map { [ length $_, $_ ] } @strings;
sort by length
@temp = sort { $a->[0] <=> $b->[0] };
grab just the strings and put them in @sorted
@sorted = map { $_->[1] } @temp;
Knowing the context of certain operationsand being able to chain them together is crucial to a deep and idiomatic understanding of Perl.

Replies are listed 'Best First'.
Re: Efficient sorting using the Schwartzian Transform
by I0 (Priest) on Jan 02, 2001 at 18:06 UTC
    You probably meant @temp = sort { $a->[0] <=> $b->[0] } @temp;

    Although, given a @temp array, it benchmarks faster to do
    @temp = map { length $_ } @strings; @sorted = @strings[sort{$temp[$a]<=>$temp[$b]} $[..$#temp];