perl hashes

B

Bart Grieten

Hi everyone, I'm not an expert Perl programmer and I'm trying to sort a
hash.
I know how to sort it by it's keys, but this time it should be sorted by its
values.

So if I have

%hash = (
Apples => 1,
apples => 4,
artichokes => 3,
Beets => 9,
);

then it should be sorted and printed in this way:

Beets 9
apples 4
artichokes 3
Apples 1

Can anyone help me with this problem?

Thanks
 
G

Gunnar Hjalmarsson

[ Do not post the same question in multiple newsgroups!! ]

Bart said:
I'm trying to sort a hash.
I know how to sort it by it's keys, but this time it should be
sorted by its values.

And if you don't know how to do that, it's good idea to look it up,
don't you think?

perldoc -f sort
 
H

hubert depesz lubaczewski

Bart Grieten wyrze¼bi³(a):
%hash = (
Apples => 1,
apples => 4,
artichokes => 3,
Beets => 9,
);
then it should be sorted and printed in this way:
Beets 9
apples 4
artichokes 3
Apples 1

using variable number of spaces make the whole thing very complicated.
yet. if the number of spaces should be the same, you simply:

for my $sKey (sort { $hash{$b} <=> $hash{$a} } keys %hash) {
printf("%s : %u\n", $sKey, $hash{$sKey});
}

depesz
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,405
Messages
2,571,545
Members
48,797
Latest member
Fractal_Prime_357
Top