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"} }',
&nbsp;&nbsp;&nbsp;&nbsp; 'age DESC'&nbsp; => 'sort { $b->{"age"} '.
                    '<=> $a->{"age"} }',
     #more sort options...
};

eval(
     '@{$foo{"bar"}} = '.
     $evals{$sort}.
     ' @{$foo{"bar"}};'
);

related:
Schwartzian transform (Wikipedia)
perlfunc (sort)
perlfunc (map)
perlref

Saturday, 04. November 2006 • trackback url

Add Comment

( to reply to a comment, click the reply link next to the comment )

Comment Title:
Your Name:
Email Address:
Make Public?
Website:
Make Public?

Comment:


Allowed XHTML tags : a, b, i, strong, code, acrynom, blockquote, abbr. Linebreaks will be converted automatically.


Captcha:

captcha image

please type the content of the above image into the following form-field: