For Programmers: Free Programming Magazines  


Home > Archive > PERL Programming > April 2004 > Hashes









You are viewing an archived Text-only version of the thread. To view this thread in it's original format and/or if you want to reply to this thread please [click here]

 

Author Hashes
Bart Grieten

2004-04-03, 12:30 pm

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


Gunnar Hjalmarsson

2004-04-03, 12:30 pm

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

Bart Grieten wrote:
> 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

--
Gunnar Hjalmarsson
Email: http://www.gunnar.cc/cgi-bin/contact.pl

Uri Guttman

2004-04-03, 12:30 pm

>>>>> "BG" == Bart Grieten <grieten.bart@skynet.be> writes:

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

hmmm, do you think you are the first person to have ever wanted to do
this before?

BG> Can anyone help me with this problem?

the FAQ can!

perldoc -q hash

and as a perl newbie, you should read the ENTIRE FAQ immediately. skip
over parts you don't understand but read it all. every little bit. then
read it again on a regular basis. there are always things to learn in
it.

uri

--
Uri Guttman ------ uri@stemsystems.com -------- http://www.stemsystems.com
--Perl Consulting, Stem Development, Systems Architecture, Design and Coding-
Search or Offer Perl Jobs ---------------------------- http://jobs.perl.org
George Bouras

2004-04-03, 5:30 pm

foreach ( sort { $hash{$b} <=> $hash{$a} } keys %hash )
{
print "$_ $hash{$_}\n"
}


Sponsored Links







Also available: Server administration forum archive | Web Design forum archive | Software forum archive | Hardware reviews archive

Copyright 2008 codecomments.com