<?xml version="1.0" encoding="windows-1252"?>
<node id="578571" title="Schwartzian Transform vs. Building Hash of Function Results, Then Sorting on Function Results" created="2006-10-16 14:54:42" updated="2006-10-16 10:54:42">
<type id="11">
note</type>
<author id="200239">
davebaker</author>
<data>
<field name="doctext">
I'm trying to better understand the Schwartzian Tranform (sorting a list by computable field). I've read the explanation in the Perl Cookbook, 2d ed. recipe 4.16. I also enjoyed &lt;a href="http://www.stonehenge.com/merlyn/UnixReview/col06.html"&gt;Randal's 1996 article in the Unix Review&lt;/a&gt;, which describes a sortable-hash technique before it goes on to show the map-sort-map transform technique.  The sortable-hash technique intrigues me.

Other than coolness and nicer-looking code, what is the advantage of this:

&lt;code&gt;    my @output =
      map { $_-&gt;[0] }
      sort { $a-&gt;[1] cmp $b-&gt;[1] }
      map { [$_, expensive_func($_)] }
    @input;&lt;/code&gt;

over this:

&lt;code&gt;    foreach $_ (@input) {
        $result_for{$_} = expensive_func($_);
    }

    my @output
        = sort { $result_for{$a} cmp $result_for{$b}
               } @input;&lt;/code&gt;
</field>
<field name="root_node">
9108</field>
<field name="parent_node">
9108</field>
</data>
</node>
