I’m having trouble trying to sort a arrayref of hashes based on a value in the hash, the data structure looks like this:
my %usera = (name => 'tom',
weight=> 10);
my %userb = (name => 'harry',
weight=> 1);
my %userc = (name => 'peter',
weight=> 5);
my $users = [];
push(@$users,\%usera,\%userb,\%userc);
I want to sort the results by weight decending, so it would come back in the order of “Tom,Peter,Harry”, but I haven’t had a lot of luck. I tried:
for my $user (sort{ $users->[$a]{'Weight'} <=> $users->[$b]{'Weight'} } @$users){
.....
}
Which I thought might have worked, but no love there.
Any idea?
TIA!
If you are sorting
@$users, your pipelined data comes in terms of elements not subscripts. So, indexing into$users->[$x]is completely unnecessary, not to mention wrong. If you had usedwarnings, you would have seenUse of reference "HASH(0x2c201e0)" as array index at ...Change your sort to:Also, as mentioned elsewhere Perl hashes are case sensitive.
$h->{Weight}and$h->{weight}are two different hash slots.