Sort keys in a hash numerically

Discussion in 'Perl Misc' started by mickey, Aug 8, 2006.

  1. mickey

    mickey Guest


    I have a has with keys like
    Char. 123
    Char. 721
    Char. 234

    and so on, that is a char followed by an integer.

    I want to iterate over the whole hash in numerical order. At present using

    foreach my $key(sort (keys %char))

    sorts them but in lexicographic order. Is there a way in Perl around that?

    mickey, Aug 8, 2006
    1. Advertisements

  2. mickey

    xhoster Guest

    If all the keys start with "Char. ", that seems pretty uninteresting.
    Why not just strip that off and store only the number?
    foreach my $key (sort {sfrn($a) <=> sfrn($b)} keys %char)

    where sfrn is Some Function that takes a key and Returns the Numberic

    xhoster, Aug 8, 2006
    1. Advertisements

  3. mickey

    usenet Guest

    perldoc -q sort

    Your question is answered in the topic:

    How do I sort an array by (anything)?
    usenet, Aug 8, 2006
  4. mickey

    Xicheng Jia Guest

    A solution with the Schwartzian Transform:

    my %hash = (
    "Char.123" => "part1",
    "Char.721" => "part2",
    "Char.234" => "part3",

    print map { "$_->[0] => $hash{$_->[0]}\n" }
    sort { $a->[1][1] <=> $b->[1][1] }
    map { [ $_, [ split/\./ ] ] }
    keys %hash;

    Xicheng Jia, Aug 8, 2006
  5. mickey

    mickey Guest

    Thanks everyone. I just stripped off the chars which made everything

    mickey, Aug 8, 2006
  6. mickey

    anno4000 Guest

    A regex capture instead of split is a little simpler:

    print map { "$_->[0] => $hash{$_->[0]}\n" }
    sort { $a->[1] <=> $b->[1] }
    map { [ $_, /(\d+)/ ] }
    keys %hash;

    anno4000, Aug 11, 2006
    1. Advertisements

Ask a Question

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

You'll need to choose a username for the site, which only take a couple of moments (here). After that, you can post your question and our members will help you out.