1: #Want to sort a complex data structure by some element
   2: #efficiently?  For example, how do you sort an array
   3: #of strings by their length?  Use the transform:
   4:    @sorted = map { $_->[1] }
   5:    sort { $a->[0] <=> $b->[0] }
   6:    map { [ length $_, $_ ] } @strings;
   7: 
   8: #Confused?  Put in temporary arrays, 
   9: #just to see what we're doing.
  10: 
  11: # create a temporary array of anonymous arrays
  12: # (0: length of the string, 1: the string)
  13:    @temp = map { [ length $_, $_ ] } @strings;
  14: # sort by length
  15:    @temp = sort { $a->[0] <=> $b->[0] };
  16: # grab just the strings and put them in @ordered
  17:    @sorted = map { $_->[1] } @temp;
  18: 
  19: #Knowing the context of certain operations
  20: # and being able to chain them together
  21: # is crucial to a deep and idiomatic
  22: # understanding of Perl.

Replies are listed 'Best First'.
Re: 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];