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

dear monks,

I have a hash with numerical values as keys and some data as values. I want to be able to retrieve the data in ascending numerical order based on the keys. My code seems to retrieve in a random order. The keys are all values from between 0 and 114. Can someone help?

my %hash = map {$nums[$_] => $sub_data[$_]} 0.. $#nums; my @gp_nums = (0..114); + + + + while ((my $key, my $value) = each %hash) { for (my $i=0; $i<@gp_nums; $i++) { if ($gp_nums[$i] == $key) { print "VALUE $value\n"; } } }

Replies are listed 'Best First'.
Re: retrieving from a hash numerically
by Ido (Hermit) on Jul 04, 2005 at 13:20 UTC
    You could simply use:
    for my $key (sort {$a<=>$b} keys %hash){ print $hash{$key} }
    But, if you have a hash with keys 0..114, why won't you just use an array?
      thanks ;-)

      this is exactly what i was after !

Re: retrieving from a hash numerically
by polettix (Vicar) on Jul 04, 2005 at 13:24 UTC
    You already have your potential keys ordered - they're 0 .. 114:
    foreach (0 .. 114) { print "VALUE $hash{$_}\n" if exists $hash{$_} }

    Flavio
    perl -ple'$_=reverse' <<<ti.xittelop@oivalf

    Don't fool yourself.
Re: retrieving from a hash numerically
by rev_1318 (Chaplain) on Jul 04, 2005 at 13:34 UTC
    print "VALUE $_\n" for @hash{1..14}; should do the trick...

    Paul

Re: retrieving from a hash numerically
by dirac (Beadle) on Jul 04, 2005 at 13:27 UTC
    my (%H, @keys, @vals);
    @vals = qw (e c a b d);
    @keys = (5, 3, 1, 2, 4);
    @H{@keys} = @vals;
    
    print map{"$_: $H{$_}\n"} sort{ $a <=> $b } keys %H;