sort { my $lhs = $lookup{$a}{val} > 0 ? "A$a" : "B$a"; my $rhs = $lookup{$b}{val} > 0 ? "A$b" : "B$b"; $lhs cmp $rhs }