in reply to sort hash elements...

If your really need the hash.. maybe this will work:

my @names_marks = ("cliff 76", "john 52", "keith 90", "rob 52"); my (%hash, @names, @marks); foreach (@names_marks) { my ($name, $mark) = split / /, $_; $hash{$_} = [ucfirst($name), $mark]; } ## then sort by the $mark foreach my $key (sort {$b->[1] <=> $a->[1]} keys %hash) { print "\$key: $key \$value: $hash{$key}->[0] $hash{$key}->[1]\n"; }

but if you only want to sort, try the Efficient sorting using the Schwartzian Transform

my @names_marks = ("cliff 76", "john 52", "keith 90", "rob 52"); my @sorted_names = map { $_->[0] } sort { $b->[1] <=> $a->[1] } map { [$_, (split(/ /, $_))[1] ] } @names_marks;

update: fixed typo in code.

Update 2: fixed missing parens in second part of code.


He who asks will be a fool for five minutes, but he who doesn't ask will remain a fool for life.

Chady | http://chady.net/

Replies are listed 'Best First'.
Re: Re: sort hash elements...
by kiat (Vicar) on Mar 27, 2002 at 13:37 UTC
    Hi chady, Thanks for helping :)

    I tried out your pieces of code. The first one does not sort the results in descending order (I forgot to mention the descending order bit) and the second one doesn't work - there is an error somewhere but I can't figure out what it was.

    Any advice?

      to sort in descending order, just reverse $a and $b.. and as for the second code.. I fixed it up, there was a missing parens.. sorry.


      He who asks will be a fool for five minutes, but he who doesn't ask will remain a fool for life.

      Chady | http://chady.net/
Re: Re: sort hash elements...
by kiat (Vicar) on Mar 28, 2002 at 09:41 UTC
    Hi Chady,

    Thanks! I tried out your second piece of code. The error is gone and I was able to print the results. However, my intention was to sort the results accoding to score in descending order, and not according to alphabetical order. Thus the output should be "Keith 90, Cliff 76, John 52, Rob 52).

    cheers,

    kiat