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

Discussion in 'Perl' started by Tommo, Dec 15, 2003.

  1. Tommo

    Tommo Guest

    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 ..
    Tommo, Dec 15, 2003
    #1
    1. Advertising

  2. Tommo wrote:
    > 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 ..


    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
    Gunnar Hjalmarsson, Dec 15, 2003
    #2
    1. Advertising

  3. Gunnar Hjalmarsson wrote:
    > Hash keys must be unique, so the way around it is to use some other
    > data structure.


    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
    Gunnar Hjalmarsson, Dec 15, 2003
    #3
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. rp
    Replies:
    1
    Views:
    517
    red floyd
    Nov 10, 2011
  2. Pål Bergström

    Sort hash with keys as integer

    Pål Bergström, Sep 25, 2010, in forum: Ruby
    Replies:
    3
    Views:
    147
    Robert Klemme
    Sep 26, 2010
  3. Malik Yousef

    Sort Hash o Hash accordint to two keys

    Malik Yousef, May 6, 2004, in forum: Perl Misc
    Replies:
    9
    Views:
    194
    Uri Guttman
    May 7, 2004
  4. Malik Yousef

    Sort Hash o Hash accordint to two keys

    Malik Yousef, May 6, 2004, in forum: Perl Misc
    Replies:
    0
    Views:
    102
    Malik Yousef
    May 6, 2004
  5. Sameer
    Replies:
    2
    Views:
    121
    Tad McClellan
    Feb 25, 2006
Loading...

Share This Page