sort hash values does not work

Discussion in 'Perl Misc' started by fatgirl.brown@gmail.com, Sep 15, 2006.

  1. Guest

    Hi, I have a two-dim array as hash value and I want to sort it:

    # <code>
    #!/usr/bin/perl -w

    push @{$hash{"test"}}, [10, "hi1"];
    push @{$hash{"test"}}, [3, "hi2"];
    push @{$hash{"test"}}, [5, "hi3"];
    push @{$hash{"test"}}, [1111, "hi4"];

    @{$hash{"test"}} = sort {$a <=> $b} @{$hash{"test"}};
    print join " ", @{$hash{"test"}[0]};
    print "\n";
    # </code>

    But it prints "5 hi3". So it put the 5 first, although the 3 should be
    first after it's sorted. How can I sort so that it's 3, 5, 10, 1111?

    Thanks!!
    Junupa
     
    , Sep 15, 2006
    #1
    1. Advertising

  2. Xicheng Jia Guest

    wrote:
    > Hi, I have a two-dim array as hash value and I want to sort it:
    >
    > # <code>
    > #!/usr/bin/perl -w
    >
    > push @{$hash{"test"}}, [10, "hi1"];
    > push @{$hash{"test"}}, [3, "hi2"];
    > push @{$hash{"test"}}, [5, "hi3"];
    > push @{$hash{"test"}}, [1111, "hi4"];
    >
    > @{$hash{"test"}} = sort {$a <=> $b} @{$hash{"test"}};


    here you are comparing two array references, to compare based on one of
    their elements, you may want to dereference them, like:

    @{$hash{"test"}} = sort { $a->[0] <=> $b->[0] } @{$hash{"test"}};

    Xicheng
     
    Xicheng Jia, Sep 15, 2006
    #2
    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. Navin
    Replies:
    1
    Views:
    704
    Ken Schaefer
    Sep 9, 2003
  2. rp
    Replies:
    1
    Views:
    539
    red floyd
    Nov 10, 2011
  3. Replies:
    3
    Views:
    211
    William James
    Nov 5, 2005
  4. hemant kumar

    how does sort work on hash

    hemant kumar, Aug 19, 2006, in forum: Ruby
    Replies:
    0
    Views:
    112
    hemant kumar
    Aug 19, 2006
  5. Tore Aursand
    Replies:
    3
    Views:
    557
    Anno Siegel
    Sep 16, 2003
Loading...

Share This Page