olecs has asked for the wisdom of the Perl Monks concerning the following question:
Hello all,
I'm having a bit of trouble sorting hashes numerically.
I create the hash entrys like this:
Everything is stored properly and I can easily access it, but I can't manage to sort $i numerically.
Here is how I (try to) do it:
Also, $k1 seem to be sorted correctly (numerically), why is this? I thought it sorted on ascii values unless asked to do otherwise with the <=> operator.
If someone could shed some light on this (particularly the sorting of $i) I would be very gratefull.
rgds,
Ole C.
I create the hash entrys like this:
For each $recNo there can be a lot of $i - both $recNo and $i are numeric.my %hash = (); $hash{$recNo} {$i} {'first'} = $currS; $hash{$recNo} {$i} {'last'} = $lastS; $hash{$recNo} {$i} {'min'} = $minA; $hash{$recNo} {$i} {'max'} = $minB;
Everything is stored properly and I can easily access it, but I can't manage to sort $i numerically.
Here is how I (try to) do it:
$k1 is in the correct order, $k2 is not (rather random it seems). If I am doing an ascii sort for $k2, like this:my $rHash = \%hash; for my $k1 = (sort keys %$rHash) #outer key, this works { for my $k2 (sort ( {keys %{rHash->{$k1}{$a}} <=> keys %{$rHash->{$k1 +}{$b}} } keys %{$rHash->{$k1}}) ) { #display miscellaneous print $k1 $k2; } }
it sorts correctly by ascii value, which doesnt help me much, but atleast indicates that it should be possible to sort it :)for my $k2 (sort keys %{$rHash->{$k1}})
Also, $k1 seem to be sorted correctly (numerically), why is this? I thought it sorted on ascii values unless asked to do otherwise with the <=> operator.
If someone could shed some light on this (particularly the sorting of $i) I would be very gratefull.
rgds,
Ole C.
|
---|
Replies are listed 'Best First'. | |
---|---|
Re: sorting hashes
by ambs (Pilgrim) on Apr 20, 2005 at 07:26 UTC | |
Re: sorting hashes
by blazar (Canon) on Apr 20, 2005 at 07:28 UTC | |
Re: sorting hashes
by Limbic~Region (Chancellor) on Apr 20, 2005 at 12:37 UTC | |
Re: sorting hashes
by johnnywang (Priest) on Apr 20, 2005 at 07:28 UTC | |
by blazar (Canon) on Apr 20, 2005 at 07:39 UTC | |
by olecs (Scribe) on Apr 20, 2005 at 07:49 UTC | |
by blazar (Canon) on Apr 20, 2005 at 13:45 UTC | |
Re: sorting hashes
by rev_1318 (Chaplain) on Apr 20, 2005 at 08:05 UTC | |
Re: sorting hashes
by TedPride (Priest) on Apr 20, 2005 at 14:17 UTC |
Back to
Seekers of Perl Wisdom