in reply to Complex conditional sort

[ I'm assuming the key is the colour's name (e.g. "Grey brown mix"). ]

Compare quantities, breaking ties by comparing names:

sort { $products{'Cat'}{'Pro'}{$a}{'Qua'} <=> $products{'Cat'}{'Pro'}{$b} +{'Qua'} || $a cmp $b } keys %{ $products{'Cat'}{'Pro'} }

Repeating $products{'Cat'}{'Pro'} all over the place is a bit silly, though.

my $pro_products = $products{Cat}{Pro}; sort { $pro_products->{$a}{Qua} <=> $pro_products->{$b}{Qua} || $a cmp $b } keys %$pro_products

Replies are listed 'Best First'.
Re^2: Complex conditional sort
by Limbic~Region (Chancellor) on Mar 09, 2011 at 00:22 UTC
    ikegami,
    Perhaps I am missing something, but I don't see how this solves the problem. The colors must be sorted alphabetically in two groups. The first group should be those with quantities above 0 and the second group should be 0. As you have described it, they will be ordered first by quantity (correctly putting all colors with quantities in front of those without) but within the groups you will have the wrong alphabetical order.

    Cheers - L~R

      Oops, I thought he wanted to group by quantity. To group by presence/absence (presence first), it's simplest to solidify the concept into values that can be compared with <=> or cmp. Let's pick zero for presence and one for absence (since zero comes before one).

      my $pro_products = $products{Cat}{Pro}; sort { $pro_products->{$a}{Qua} ?0:1 <=> $pro_products->{$b}{Qua} ?0:1 || $a cmp $b } keys %$pro_products

      Update: Down below, L~R picked "A" and "B" instead of 0 and 1. Same idea.