Doraemon has asked for the wisdom of the Perl Monks concerning the following question:
%unsorted_hash = (k1=> 'v2', k2=> 'v1'); sortvalues(\@sorted, \%unsorted_hash); foreach (@sorted,) { print "$unsorted_hash{$_}\n"; } #---------------------------------- # sorting hashes based on values # in : array of sorted keys (output), hashes to use # out : none #---------------------------------- sub sortvalues($$) { my ($sorted, $hashes) = @_; sub swap($$) { my ($a, $b) = @_; my $temp = $$a; $$a = $$b; $$b = $temp; } for my $loop (0..(scalar @$sorted - 1)) { my $ub = scalar @$sorted - $loop - 2; for my $i (0..$ub) { if (($$hashes{$$sorted[$i]} <=> $$hashes{$$sorted[$i+1]}) > + 0 ) { swap (\$$sorted[$i], \$$sorted[$i+1]); } } } }
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Want to sort hashes by values, anyone?
by dragonchild (Archbishop) on May 11, 2004 at 14:37 UTC | |
by Doraemon (Beadle) on May 11, 2004 at 15:12 UTC | |
|
Re: Want to sort hashes by values, anyone?
by runrig (Abbot) on May 11, 2004 at 14:38 UTC | |
by Doraemon (Beadle) on May 11, 2004 at 15:30 UTC | |
by dragonchild (Archbishop) on May 11, 2004 at 17:24 UTC | |
by runrig (Abbot) on May 12, 2004 at 17:17 UTC | |
by Doraemon (Beadle) on May 12, 2004 at 01:35 UTC | |
|
Re: Want to sort hashes by values, anyone?
by Zaxo (Archbishop) on May 11, 2004 at 14:41 UTC | |
|
Re: Want to sort hashes by values, anyone?
by Limbic~Region (Chancellor) on May 11, 2004 at 15:18 UTC |