Schwartzian transform
we wanted to dynamically sort an array of hashes in perl. some of the contents to sort were strings and we wanted to do a case-insensitive search. we use the Schwartzian transform named after Randal L. Schwartz, who first demonstrated it in perl. example:
we expect a scalar $sort to this script.
%evals = {
#the next 2 values are Schwartzian transforms
'name ASC' => 'map { $_->[0] } '.
'sort { $a->[1] cmp $b->[1] } '.
'map { [ $_ , lc($_->{"name"}) ] }',
'name DESC' => 'map { $_->[0] } '.
'sort { $b->[1] cmp $a->[1] } '.
'map { [ $_ , lc($_->{"name"}) ] }',
'age ASC' => 'sort { $a->{"age"} '.
'<=> $b->{"age"} }',
'age DESC' => 'sort { $b->{"age"} '.
'<=> $a->{"age"} }',
#more sort options...
};
eval(
'@{$foo{"bar"}} = '.
$evals{$sort}.
' @{$foo{"bar"}};'
);
related:
Schwartzian transform (Wikipedia)
perlfunc (sort)
perlfunc (map)
perlref

