Schwartzian Transform - The Perl Idiom

The Perl Idiom

The general form of the Schwartzian Transform is:

@sorted = map { $_-> } sort { $a-> cmp $b-> } map { } @unsorted;

Where foo($_) represents an expression that takes $_ (each item of the list in turn) and produces the corresponding value that is to be compared in its stead.

Reading from right to left (or from the bottom to the top):

  • the original list @unsorted is fed into a map operation that wraps each item into a (reference to an anonymous 2-element) array consisting of itself and the calculated value that will determine its sort order (list of item becomes a list of );
  • then the list of lists produced by map is fed into sort, which sorts it according to the values previously calculated (list of ⇒ sorted list of );
  • finally, another map operation unwraps the values (from the anonymous array) used for the sorting, producing the items of the original list in the sorted order (sorted list of ⇒ sorted list of item).

The use of anonymous arrays ensures that memory will be reclaimed by the Perl garbage collector immediately after the sorting is done.

Read more about this topic:  Schwartzian Transform

Famous quotes containing the word idiom:

    Psychobabble is ... a set of repetitive verbal formalities that kills off the very spontaneity, candor, and understanding it pretends to promote. It’s an idiom that reduces psychological insight to a collection of standardized observations, that provides a frozen lexicon to deal with an infinite variety of problems.
    Richard Dean Rosen (b. 1949)