in reply to Choosing "best" - sorting hashes issue

The previous answer about an embedded database was appropriate, however, a HoA structure might also be appropriate if you don't need persistence. I just built one, so here it is: Hash has UNIX commands as keys. For each hash key, I save an anonymous array of two cells (recent history, and popularity) as value. I then need to sort that hash based on one or the other.
read a file line into $line, then: my @arry = split(/==/, $line); #recent==pop==commandname $myhash{$arry[$#arry]} = [$arry[0], $arry[1]]; loop until done to sort: my @recentkeys = sort by_HoA_0_asc keys(%myhash); my @popkeys = sort by_HoA_1_desc keys(%myhash); # sort Hash of Arrays by numeric value of first # array value(history), ascending sub by_HoA_0_asc { if ($myhash{$a}[0] < $myhash{$b}[0]) { return -1; } elsif ($myhash{$a}[0] > $myhash{$b}[0]) { return 1; } return 0; } # sort Hash of Arrays by numeric value of second # array value (popularity), descending. If equal, # sort by first array value (history), ascending. sub by_HoA_1_desc { if ($myhash{$a}[1] > $myhash{$b}[1]) { return -1; } elsif ($myhash{$a}[1] < $myhash{$b}[1]) { return 1; } if ($myhash{$a}[0] < $myhash{$b}[0]) { return -1; } elsif ($myhash{$a}[0] < $myhash{$b}[0]) { return 1; } return 0; }

Replies are listed 'Best First'.
Re^2: Choosing "best" - sorting hashes issue
by dave_the_m (Monsignor) on Jan 14, 2005 at 22:18 UTC
    by_HoA_1_desc can be written more succinctly as
    $myhash{$a}[1] <=> $myhash{$b}[1] || $myhash{$a}[0] <=> $myhash{$b}[0]

    Dave.

      True. I'm still getting used to da spaceship. :)

      One question, how does it compare efficiency-wise to if-elseif chains?
      Ummm... in my case, since popularity is sorted in descending order and history needs to be sorted in ascending order, shouldn't it be:
      $myhash{$b}[1] <=> $myhash{$a}[1] || $myhash{$a}[0] <=> $myhash{$b}[0]
      ?

      In any event, thanks for suggesting the improvement. In my long-winded if-elsif chained version, I had one of the >'s reversed, leading to a very dirty bug.