Paul said:
Alf McLaughlin wrote:
Alf,
Please learn to quote properly. Post your reply *below* the quoted
text, after trimming it down to the relevant bits. Thank you.
[quoting fixed below]
(e-mail address removed) wrote:
Alf McLaughlin wrote:
[Subject: Sorting a Hash of Arrays by an Element in the Array]
for my $key (sort {$hash{$a}->[0] <=> $hash{$b}->[0]} keys %hash) {
print "$key\n";
}
Am I missing something??? It looks as if it can be done to me.
I dunno. Run this program and tell me what you are trying to say:
#!/usr/bin/perl
use strict; use warnings;
my %hash = (col=>[qw/red yellow green/],
make=>[qw/ford chevy/],body=>[qw/coupe sedan/]);
for my $key (sort {$hash{$a}->[0] cmp $hash{$b}->[0]} keys %hash) {
print "$key\n";
}
__END__
I am trying to say you will see the keys printed in the order the 1st
element of the array will be sorted in. I tried this and it worked for
me:
body (coupe is the earliest in the alphabet)
make (ford is the middle)
col (red is the last in the alphabet)
Okay, so obviously that *does* work. So what are you getting at?
Where are these "old questions" you claim to have seen that gave an
incorrect answer? Are you sure they're asking the same thing you're
asking? Give us a point of reference.
Actually, this surprised me because I
only expected numbers to sort correctly.
Your example would only sort numbers correctly. David's would only
sort strings correctly. They are not the same. Yours used the <=>
operator, while David's used the cmp operator.
I think it may not be sorting
the words correctly, but I'm sure it works for numbers.
Now you've completely lost me. You saw David's example, verified that
it worked, but suddenly you're not sure if it sorted the words
correctly?
Paul Lalli
Apologies for the misquoting. This better?
Ah, I've lost you due to my own ignorance. I did not catch that he
changed "<=>" to "cmp"; sorry for the confusion.
I do not have time to dig up old questions for you, but I casually
noticed that some people like to answer this question as "this cannot
be done because you cannot guarantee keys in a hash are stored in a
sorted manner... etc etc". Well, I know that and it's good to know,
but since you can always sort a hash who really cares? The point of me
asking this is actually simple: Can I be guranteed that sorting a Hash
of Arrays like this (on an array element) will always work? That's
really my question. Again, my apologies (this posting has gotten a lot
more apologetic than I had originally intended- from now on I apologize
for nothing in this post! So there.)
But, I have a new question now that is a logical extension of this.
Suppose I have a Hash of a Hash of arrays. Is there a way to sort this
by an element in the array? I know I can write my own subroutine to
create a new hash and sort it that way (or whatever- MTOWTDI), but I
was just curious.
Thanks,
Alf