Re: Sorting a hash

[email protected] (Iain Adams)
Newsgroups perl.beginners
Organization http://groups.google.com
Message-ID <[email protected]>
On Jun 2, 8:43 pm, [email protected] (Jialin Li) wrote:
> On Mon, Jun 2, 2008 at 1:53 PM, Iain Adams <[email protected]> wrote:
> > Hello,
>
> > I am trying to sort a hash of hashes.
>
> > my code looks like this
>
> >  foreach $cnt (sort keys %{ $relations{ $uid }{ "instances" } }){
> >             print OUT "$cnt 1, ";
> >  }
>
> > This prints out the correct numbers (the keys of the instances hash.
> > However the sorting is a bit weird.  The keys are all integers yet
> > when sorting the keys aren't put in number order. instead the first
> > digit is seen as the qualifier.
>
> > Here is an example output:
>
> >  100 1, 120 1, 121 1, 122 1, 123 1, 124 1, 125 1, 126 1, 127 1, 132 1,
> > 133 1, 134 1, 135 1, 136 1, 137 1, 138 1, 139 1, 221 1, 222 1, 223 1,
> > 224 1, 225 1, 226 1, 227 1, 228 1, 235 1, 236 1, 237 1, 238 1, 239 1,
> > 240 1, 241 1, 242 1, 323 1, 324 1, 325 1, 326 1, 327 1, 328 1, 329 1,
> > 330 1, 50 1, 51 1, 52 1, 53 1, 54 1, 55 1, 56 1, 57 1, 93 1, 94 1, 95
> > 1, 96 1, 97 1, 98 1, 99 1,
>
> > As you can see it is not in normal order.
>
> > Does anyone know why this is happening and how I can fix it?
>
> > Thanks
>
> > --
> > To unsubscribe, e-mail: [email protected]
> > For additional commands, e-mail: [email protected]
> >http://learn.perl.org/
>
> to numerically sort, you should use:
>
> sort { $a <=> $b } keys %{ $relations{ $uid }{ "instances" }  }
>
> when you omit { $a <=> $b }, perl is using default string comparison:
> { $a cmp $b}
>
> Jialin

Thanks Jialin thats great!
lmpx.com only provides a reader for public news (NNTP) servers. It is not affiliated with the servers or forums shown here and is not responsible for the content of articles, which is written by their respective authors.