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

I am trying to put values into a hash. I know that some will have the same keys, but different values. I am trying to increment the keys, which have numerical values, so that they won't overwrite each other but still be close in value. Somehow they keep getting overwritten.
if(defined $hash{$key}) { $key = $key + .0000001 until !defined $hash{$key}; $hash{$key} = $value; } else { $hash{$key} = $value; }

Replies are listed 'Best First'.
Re: incrementing hash values
by thor (Priest) on Dec 24, 2004 at 03:54 UTC
    So what you're trying to do is store multiple values for a given key. If it were me, I'd use a hash of arrays. Like so:
    push @{$hash{$key}}, $value
    Then, to extract them, you'd do something like this:
    foreach my $key (keys %hash) { print "$key =>\n" foreach my $thing (@{$hash{$key}}) print "\t$thing\n"; } }

    thor

    Feel the white light, the light within
    Be your own disciple, fan the sparks of will
    For all of us waiting, your kingdom will come

Re: incrementing hash values
by Aristotle (Chancellor) on Dec 24, 2004 at 03:54 UTC

    If $value can be undefined, your check will be testing for the wrong thing. Use exists instead of defined.

    But that's still klunky. Instead try

    push @{ $hash{ $key } }, $value;

    Now the value for each key will be an array reference containing all the different values.

    Makeshifts last the longest.

Re: incrementing hash values
by rev_1318 (Chaplain) on Dec 24, 2004 at 13:19 UTC
    As others have pointed out, you probably should use a hash of arrays to store the values.

    I think the problem you are encountering, has to do with the representatio of floating point numbers. 100.0000001 may or may not be represented different internally as,say, 100.0000002, so you have no garantee that the keys will differ.

    Paul

      But his until !defined $hash{$key} fails so long as incrementing does not change the stringified value of $key. He might get an infinite loop, but it can't be the reason for entries in the hash getting overwritten.

      Makeshifts last the longest.

Re: incrementing hash values
by Anonymous Monk on Dec 24, 2004 at 23:39 UTC
    How do you preform operations on the array then. For example, how would you do scalar. Also how do you print individual array elements without foreach? Thanks for the help.