http://qs321.pair.com?node_id=578571


in reply to Schwartzian Transform

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 Randal's 1996 article in the Unix Review, 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:
my @output = map { $_->[0] } sort { $a->[1] cmp $b->[1] } map { [$_, expensive_func($_)] } @input;
over this:
foreach $_ (@input) { $result_for{$_} = expensive_func($_); } my @output = sort { $result_for{$a} cmp $result_for{$b} } @input;