PDA

View Full Version : Sorting Array of Hash refs


tom123
09-17-2007, 12:03 PM
Hi

I have the following structure:

While ($whatever) {
my %entry = ( 'judge_id' => $$judge{'judge_id'},
'judge_name' => $$judge{'name'},
'category' => $$judge{'products'}{$code},
'num_entries' => $count[0],
);

push(@entries,\%entry);
}

I need to sort the structure by hash key "category".

Doing the following dosent work:

my @entries = sort ({ $entries{$a}->{'category'} cmp $entries{$b}->{'category'} } @entries);

Any Ideas?

FishMonger
09-17-2007, 06:45 PM
Do you need to use the array? It might be easier/better to use a hash instead of the array.

While ($whatever) {
my %entry = ( 'judge_id' => $$judge{'judge_id'},
'judge_name' => $$judge{'name'},
'category' => $$judge{'products'}{$code},
'num_entries' => $count[0],
);

$category{$$judge{'products'}{$code}} = \%entry; # untested
}

Then you can do a normal/simple sort on the %category keys.

FishMonger
09-17-2007, 06:53 PM
Or, you could try:

push @{$category{$$judge{'products'}{$code}}}, \%entry; # untested

tom123
09-18-2007, 01:24 PM
Good idea Fishmonger

I actually need it as an array.
I changed it to an hash as above, and then looped though the hash sorting by key and placed contents back into array.

my %entry = ( 'judge_id' => $$judge{'judge_id'},
'judge_name' => $$judge{'name'},
'category' => $$judge{'products'}{$code},
'num_entries' => $count[0],
);
$cats{$$judge{'products'}{$code}} = \%entry;

# Get list of cartegorys
my %categoryList = &get_judges_unscored_entries( $db, \@judges, $params{'Award_Id'} );

my @cat_list;
foreach my $key( sort {$a cmp $b} keys %categoryList )
{
push(@cat_list,$categoryList{$key})

}
Thanks