'map' and schwartzian transforms

Dan.Sherer at wellpoint.com Dan.Sherer at wellpoint.com
Wed Aug 30 20:43:00 CDT 2000


With regards to Mark's comments yesterday about the complexity of Randal
Schwartz's use of the "map" command to sort a list.


I did some research and found another author who uses that code and has
created a nice explaination of it.  He named the algorithm "The Schwartzian
Transform" in honor of its author.

Check out his description at http://www.5sigma.com/perl/schwtr.html

His book is called "Effective Perl Programming" by Joseph N. Hall


A sample "Schwartzian Transform" is:

   @sorted_by_size =
     map { $_->[0] }
     sort { $a->[1] <=> $b->[1] }
     map { [$_, -s] }
     @files;


As it turns out, the most important thing to know about this is that the "key
field" is determined by what you include to the bottom-most sort.  In this
example, "-s" is used.  That is (of course) the file test to report size, in
bytes.

The second most important thing is the operator and the order of keys in the
sort statement.

In this case, we're using "<=>" which means "compare numbers".  And, we've
listed the sort parameters ($a and $b) in ASCENDING order.  So the sort will
be from smallest file to largest. (duh!)

Slightly intimidating.  Very fast and "powerful".  Very Perl-ish!


Daniel



More information about the Thousand-oaks-pm mailing list