perl hashes

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

    perl hashes

    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



  • Gunnar Hjalmarsson

    #2
    Re: perl hashes

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

    Bart Grieten wrote:[color=blue]
    > 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.[/color]

    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

    Comment

    • hubert depesz lubaczewski

      #3
      Re: perl hashes

      Bart Grieten wyrze¼bi³(a):[color=blue]
      > %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[/color]

      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:

      Comment

      Working...