Re: Sorting AofH over hash key(s)...



/usr/ceo wrote:
I've searched this NG, the web, and CPAN and haven't seen anything to
do this, and while I have a solution, I'm wondering what other
solutions might be living inside some other pretty brilliant brain
cages here on c.l.p.m...

The problem seems fairly straight-forward: I want to be able to sort
an Array of Hashes by an arbitrary number of hash keys. For instance,
given this hash:

my $h = [
{ color => 'red', size => 1, width => 640, height => 480 },
{ color => 'blue', size => 4, width => 800, height => 600 },
{ color => 'green', size => 2, width => 1024, height => 768 },
{ color => 'orange', size => 5, width => 320, height => 280 },
{ color => 'purple', size => 3, width => 40, height => 50 },
];

I'd like to sort by the keys: color, size, width, and/or height. I
realize for only ONE hash key, I can do:

for my $info (sort { $a->{color} cmp $b->{color} } @{$h}) { blah() }
#...

But... What if I want to sort by say... color and then size? Or
height and then width? Or all the keys in some order?

Just modify the sort to take into account the other keys.

sort {
$a->{ 'color' } cmp $b->{ 'color' } ||
$a->{ 'size' } <=> $b->{ 'size' }
}@{$h};

perldoc -q "How do I sort"
.



Relevant Pages

  • Re: Sorting AofH over hash key(s)...
    ... cages here on c.l.p.m... ... I want to be able to sort ... an Array of Hashes by an arbitrary number of hash keys. ... # is like saying use 'cmp' to compare the first key ...
    (comp.lang.perl.misc)
  • Re: Sorting AofH over hash key(s)...
    ... cages here on c.l.p.m... ... I want to be able to sort ... an Array of Hashes by an arbitrary number of hash keys. ... # is like saying use 'cmp' to compare the first key ...
    (comp.lang.perl.misc)
  • Re: Ordering string of commands in a file
    ... you may need to reset $/ to read your data, and then use hash keys to ... sort your results. ... use strict; ...
    (comp.lang.perl.misc)
  • Re: Sorting AofH over hash key(s)...
    ... an Array of Hashes by an arbitrary number of hash keys. ... I'd like to sort by the keys: ... Also, my example, with a lot of numeric data is somewhat bad, I ...
    (comp.lang.perl.misc)