perl hashes

Discussion in 'Perl' started by Bart Grieten, Apr 3, 2004.

  1. Bart Grieten

    Bart Grieten Guest

    Hi everyone, I'm not an expert Perl programmer and I'm trying to sort a
    hash.
    I know how to sort it by it's keys, but this time it should be sorted by its
    values.

    So if I have

    %hash = (
    Apples => 1,
    apples => 4,
    artichokes => 3,
    Beets => 9,
    );

    then it should be sorted and printed in this way:

    Beets 9
    apples 4
    artichokes 3
    Apples 1

    Can anyone help me with this problem?

    Thanks
     
    Bart Grieten, Apr 3, 2004
    #1
    1. Advertising

  2. [ Do not post the same question in multiple newsgroups!! ]

    Bart Grieten wrote:
    > I'm trying to sort a hash.
    > I know how to sort it by it's keys, but this time it should be
    > sorted by its values.


    And if you don't know how to do that, it's good idea to look it up,
    don't you think?

    perldoc -f sort

    --
    Gunnar Hjalmarsson
    Email: http://www.gunnar.cc/cgi-bin/contact.pl
     
    Gunnar Hjalmarsson, Apr 3, 2004
    #2
    1. Advertising

  3. Bart Grieten wyrze¼bi³(a):
    > %hash = (
    > Apples => 1,
    > apples => 4,
    > artichokes => 3,
    > Beets => 9,
    >);
    > then it should be sorted and printed in this way:
    > Beets 9
    > apples 4
    > artichokes 3
    > Apples 1


    using variable number of spaces make the whole thing very complicated.
    yet. if the number of spaces should be the same, you simply:

    for my $sKey (sort { $hash{$b} <=> $hash{$a} } keys %hash) {
    printf("%s : %u\n", $sKey, $hash{$sKey});
    }

    depesz

    --
    *-----------------------------------------------------------------*
    czaderskie dywaniki do ³azienki lub przed ³ó¿ko:
    http://www.allegro.pl/show_user_auctions.php?uid=118670
     
    hubert depesz lubaczewski, Apr 3, 2004
    #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. Ben Holness

    Hashes of Hashes via subs

    Ben Holness, Oct 5, 2003, in forum: Perl
    Replies:
    8
    Views:
    589
    Ben Holness
    Oct 8, 2003
  2. Steven Arnold

    using hashes as keys in hashes

    Steven Arnold, Nov 23, 2005, in forum: Ruby
    Replies:
    3
    Views:
    183
    Mauricio Fernández
    Nov 23, 2005
  3. kazaam
    Replies:
    12
    Views:
    294
    Matthias Wächter
    Sep 13, 2007
  4. Neela megha shyam Chivukula

    On Hashes - How the hashes printing works?

    Neela megha shyam Chivukula, May 27, 2009, in forum: Ruby
    Replies:
    4
    Views:
    279
    Markus Schirp
    May 28, 2009
  5. Tim O'Donovan

    Hash of hashes, of hashes, of arrays of hashes

    Tim O'Donovan, Oct 27, 2005, in forum: Perl Misc
    Replies:
    5
    Views:
    233
Loading...

Share This Page