Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

Dear Monks, I have a %hash containing a sets of numbers as keys and values. I need to numerically sort the keys and then extract keys and values (into different arrays) according to this order. I don't see why my effort below doesn't work(!) - it keeps the values in the order that they're in the hash (which don't correspond to the keys)!? Can anyone could help??
while ((my $key, my $value) = each (%hash)) { for (my $i=0; $i< @nums; $i++) { if ($key eq $nums[$i]) { push @temps, "$key"; } } } @temps = sort {$a<=>$b} @temps; while ((my $key, my $value) = each (%hash)) { for (my $i=0; $i < @temps; $i++) { if ($key eq $temps[$i]) { push @fluors, "$value"; } } }

Replies are listed 'Best First'.
Re: Hashes - sorting keys
by davorg (Chancellor) on Jul 15, 2003 at 10:15 UTC
    my @temps = sort { $a <=> $b } keys %hash; my @fluors = @hash{@temps};
    --
    <http://www.dave.org.uk>

    "The first rule of Perl club is you do not talk about Perl club."
    -- Chip Salzenberg

      You should explain it to him.

        What needs explaining?

        # get a sorted list of hash keys and store in array @temps my @temps = sort { $a <=> $b } keys %hash; # use a hash slice to get list of values in the same order # as the keys in @temps and store in array @fluors my @fluors = @hash{@temps};
        --
        <http://www.dave.org.uk>

        "The first rule of Perl club is you do not talk about Perl club."
        -- Chip Salzenberg

Re: Hashes - sorting keys
by Skeeve (Parson) on Jul 15, 2003 at 10:32 UTC
    I don't understand what your first loop should do. Currently it stores alle the hash keys in @temp if they (by incident) are equal to a value in an array @nums.

    Your code for sorting is fine, but you don't sort all hashkeys but just those picked in your first loop. To sort all of them you can use, as davorg already said:

    my @temps = sort { $a <=> $b } keys %hash;
    Your second loop looks similar to the first one. Again you compare the randomly ordered hashkeys with the numbers stored in an array (@temps).

    This won't get you very far. If you need all the values of your hash, you can get them, again as davorg stated

    @fluors= @hash{@temps};
    BTW: If you deal with numbers and want to compare them, you should use == instead of eq. Simply because 0.0 == 0 but "0.0" ne "0"