[sf-perl] Happy fun sorting problem

Chris Palmer chris at noncombatant.org
Fri Jun 10 13:07:46 PDT 2005


David Fetter writes:

> > To further complicate things, the "Category" level is being sorted
> > according to an external ordering list and not alphabetically.
> 
> perldoc perlfaq4 goes into this in detail :)

Thanks for the pointer, David; I hadn't seen that one before.

It gives the answer I was going to give:

    @sorted = sort { field1($a) <=> field1($b) ||
                     field2($a) cmp field2($b) ||
                     field3($a) cmp field3($b)
                    }     @data;

which I find quite elegant. In Josh's case, he'll want to use the
literal Subcategory and Item values in the cmp/<=> expressions, instead
of fieldX functions. For the Category sorting, which he notes is ordered
according to an external list, I would replace the first compare
statement in the above with:

    %category_order = (foo => 1, bar => 2, ...);
    ...
    @sorted = sort {
        $category_order{$ctgry_a} <=> $category_order{$ctgry_b} ||
        other comparisons ... } @data;



More information about the SanFrancisco-pm mailing list