How can you sort non-unique 'numeric keys' in a Perl hash

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Tommo

    How can you sort non-unique 'numeric keys' in a Perl hash

    Hello All,
    I have a slight problem that goes like this. I have created
    a Perl hash where the keys are made up of numeric values, I was then
    sorting the 'keys' for this hash on their value (a<=>b etc), all was
    well until I got 2 keys with the same value, I seem to loose one of
    the hash entries. Is there a way around this problem ..

    cheers, Mark ..
  • Gunnar Hjalmarsson

    #2
    Re: How can you sort non-unique 'numeric keys' in a Perl hash

    Tommo wrote:[color=blue]
    > I have created a Perl hash where the keys are made up of numeric
    > values, I was then sorting the 'keys' for this hash on their value
    > (a<=>b etc), all was well until I got 2 keys with the same value, I
    > seem to loose one of the hash entries. Is there a way around this
    > problem ..[/color]

    Hash keys must be unique, so the way around it is to use some other
    data structure.

    --
    Gunnar Hjalmarsson
    Email: http://www.gunnar.cc/cgi-bin/contact.pl

    Comment

    • Gunnar Hjalmarsson

      #3
      Re: How can you sort non-unique 'numeric keys' in a Perl hash

      Gunnar Hjalmarsson wrote:[color=blue]
      > Hash keys must be unique, so the way around it is to use some other
      > data structure.[/color]

      A hash of arrays, maybe:

      my %hash = (
      1 => [ 130 ],
      2 => [ 100, 125 ],
      3 => [ 120 ],
      );

      for ( sort { $hash{$a}->[0] <=> $hash{$b}->[0] } keys %hash ) {
      print "$_: ", ( join ', ', @{$hash{$_}} ), "\n";
      }

      --
      Gunnar Hjalmarsson
      Email: http://www.gunnar.cc/cgi-bin/contact.pl

      Comment

      Working...