Re: Sorting AofH over hash key(s)...
- From: Mirco Wahab <wahab-mail@xxxxxx>
- Date: Tue, 30 Oct 2007 22:03:03 +0100
/usr/ceo wrote:
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? Again haven't
seen anything to do this. It's hard to imagine this has never been
solved, but then again, I've done a fair amount of Perl coding in my
day and I haven't run across the need to do this until recently.
The (somehow) canonical solution would be a sorter function like:
...
my @hs = sort mysortorder @$h;
sub mysortorder {
$a->{color} cmp $b->{color} ||
$b->{width} <=> $a->{width} ||
$b->{height} <=> $a->{height} ||
$b->{size} <=> $a->{size}
}
for my $s (@hs) {
print "$_=>$s->{$_}, " for keys %$s;
print "\n"
}
...
Regards
M.
.
- References:
- Sorting AofH over hash key(s)...
- From: /usr/ceo
- Sorting AofH over hash key(s)...
- Prev by Date: Re: Regular Expression and Useage
- Next by Date: Re: Sorting AofH over hash key(s)...
- Previous by thread: Sorting AofH over hash key(s)...
- Next by thread: Re: Sorting AofH over hash key(s)...
- Index(es):
Relevant Pages
|