in reply to sort an array of hashes by value

Another idea for you... Maintaining the two tables in sync is a hassle. I was just keying upon I would like to sort @food by putting all non-fruit at the end. Doesn't solve the ranking problem within FRUIT, I just used alpha sort.
#!/usr/bin/perl use strict; use warnings; use Data::Dumper; use constant FRUIT => 0; use constant VEGGIE =>1; my @food; push @food, { name => "apple", type => FRUIT }; push @food, { name => "banana", type => FRUIT }; push @food, { name => "orange", type => FRUIT }; push @food, { name => "broccoli", type => VEGGIE }; push @food, { name => "grape", type => FRUIT }; my @sorted = sort { $a->{type} <=> $b->{type} or $a->{name} cmp $b->{name} } @food; print Dumper(\@sorted); __END__ $VAR1 = [ { 'name' => 'apple', 'type' => 0 }, { 'type' => 0, 'name' => 'banana' }, { 'type' => 0, 'name' => 'grape' }, { 'name' => 'orange', 'type' => 0 }, { 'type' => 1, 'name' => 'broccoli' } ];
Update: As a practical matter, part of my thinking is that a data structure like this:
my %ranking = ( 1 => 0, 2 => 1, 5 => 2, 10 =>3 );
will be very hard to maintain manually. Here it is possible. But if the tables grow to any size, it won't be feasible and some other structure will be needed to describe the rankings that a human can deal with.

Replies are listed 'Best First'.
Re^2: sort an array of hashes by value
by micmac (Acolyte) on Jul 14, 2016 at 20:38 UTC
    Great tips, you are right about the maintainability. Thank-you!