in reply to Re: how do I sort on two fields in a hash table?
in thread how do I sort on two fields in a hash table?

I believe your or binds too loosely so you get:
( sort {$b->{'count'} cmp $a->{'count'} ) or $b->{'type'} cmp $a->{'type'}} @data
(Note the parentheses above indicating the binding).

What you want is:

sort {$b->{'count'} <=> $a->{'count'} || $b->{'type'} cmp $a->{'type'}} @data
Which binds more tightly. I also flipped the comparison operator for count since as dvergin pointed out above you probably want a numeric comparison for count.

-ben

Replies are listed 'Best First'.
Re: Re: Re: how do I sort on two fields in a hash table?
by lhoward (Vicar) on Mar 16, 2001 at 01:43 UTC
    I don't think so... my test program:
    #!/usr/bin/perl -w use strict; my @a; push @a,{x=>1,y=>1}; push @a,{x=>2,y=>1}; push @a,{x=>1,y=>2}; push @a,{x=>2,y=>3}; push @a,{x=>2,y=>2}; foreach(sort {$a->{x} <=> $b->{x} or $a->{y} <=> $b->{y}} @a){ print " $_->{x} $_->{y}\n"; }
    prints the correct results:
    $ ./sort.pl 1 1 1 2 2 1 2 2 2 3
Re: Re: Re: how do I sort on two fields in a hash table?
by vonman (Acolyte) on Mar 16, 2001 at 00:50 UTC
    Thanks for your response. I thought that || was the same as or. How are they different? Txs

      They do the same thing, it's all about operator precedence. || has higher precedence than or, and other things in between. The perlop manpage has about everything you need to know. To steal an example from perlop, the following:
          unlink "alpha", "beta", "gamma" or gripe(), next LINE;
      works like:
          unlink("alpha", "beta", "gamma") or (gripe(), next LINE);
      but it would break using ||, because it would work like:
          unlink("alpha", "beta", ("gamma" || gripe()), next LINE;