in reply to Sorting on Exists

You're doing two separate sorts. Which sorts by the first criteria and then resorts by the second criteria (completely ignoring the first).

If you want to sort by two criteria then you need to do both comparisons in the same sorting block.

use strict; use warnings; my @data = ( { vtype_ug => 1, total_rate => 400, }, { total_rate => 220, }, { total_rate => 700, vtype_ug => 1, }, { total_rate => 300, }, { total_rate => 400, }, { total_rate => 250, }, ); my @sorted = sort { -(exists $a->{vtype_ug} <=> exists $b->{vtype_ug}) || $a->{total_rate} <=> $b->{total_rate} } @data; use Data::Dumper; print Dumper @sorted;

Note: The negation on the first comparison ensures that elements with "vtype_ug" come before those who don't (without it the order is reversed).

--
<http://dave.org.uk>

"The first rule of Perl club is you do not talk about Perl club."
-- Chip Salzenberg

Replies are listed 'Best First'.
Re^2: Sorting on Exists
by bart (Canon) on Sep 09, 2006 at 20:16 UTC
    You're doing two separate sorts. Which sorts by the first criteria and then resorts by the second criteria (completely ignoring the first).
    No, that's not true. His first (last executed) sort code block is wrong, but in a modern perl, i.e. one with a table sort, the concept is valid: you can sort items according to one field, while keeping items that compare to the same value in their original order. Just like sgifford shows in Re: Sorting on Exists.