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.
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Re: sort hash elements...
by kiat (Vicar) on Mar 27, 2002 at 13:37 UTC | |
by Chady (Priest) on Mar 27, 2002 at 18:01 UTC | |
|
Re: Re: sort hash elements...
by kiat (Vicar) on Mar 28, 2002 at 09:41 UTC |